简体   繁体   English

二叉搜索树中每个分支的总和

[英]Sum of Each Branch in a Binary Search Tree

My assignment is to find the sum of all nodes on each branch in a binary search tree using recursion, and compare them to a user input value.我的任务是使用递归找到二叉搜索树中每个分支上所有节点的总和,并将它们与用户输入值进行比较。 If the user input value matches a sum of one of the branches, the function should return true.如果用户输入值与其中一个分支的总和相匹配,则该函数应返回 true。

二叉搜索树

In other words, the sum of 32+24+21+14=91.也就是说,32+24+21+14之和=91。 The sum of 32+24+28+25=109. 32+24+28+25的总和=109。 The sum of 32+24+28+31=115 etc. I have tried many different methods, but cant seem to figure out how to traverse each branch accurately. 32+24+28+31=115等的总和。我尝试了很多不同的方法,但似乎无法弄清楚如何准确遍历每个分支。 So far I have only been able to traverse and find the sum of the left-most branch.到目前为止,我只能遍历并找到最左边分支的总和。

I am using the method of subtracting each node from the user input value.我正在使用从用户输入值中减去每个节点的方法。 If the value reaches 0 at a Leaf-node, then clearly the user-input matches the node-sum of that branch on the tree.如果叶节点处的值达到 0,则显然用户输入与树上该分支的节点和相匹配。

The particular points of difficulty for me are when the branch diverges, such as at the node [24] and [28].对我来说特别困难的点是分支何时发散,例如在节点 [24] 和 [28] 处。 I clearly am getting something very simple wrong, but I cant figure it out.我显然犯了一些非常简单的错误,但我无法弄清楚。

Below is the condensed code I've written so far, in the form of two companion methods (also required for the assignment).下面是我到目前为止编写的精简代码,采用两个伴随方法的形式(也是作业所必需的)。

public:
bool findBranchSum1(int value) throw (InvalidTreeArgument) {
    if (root == nullptr)
        throw InvalidTreeArgument();
    return(findBranchSum(root, value));
}

private:
bool findBranchSum(NodePtr node, int value) throw (InvalidTreeArgument)
{
    bool result = false;
    if (root == nullptr)
        throw InvalidTreeArgument();

    value -= node->getElement(); //subtract current node from user-input value. 

    cout << "Current Value = " << value << endl; //help track value changes

    if (node->getLeftSide() == nullptr && node->getRightSide() == nullptr)
        {
            if (value == 0)
            {
                result = true;
                return(true);
            }
            else
                return(false);
        }
    else
    {
        if (node->getLeftSide() != nullptr)
        {
            node = node->getLeftSide(); //advance to next Left node
            result = findBranchSum(node, value); //recursive call using new node
        }
        if (node->getRightSide() != nullptr)
        {
            node = node->getRightSide(); //advance to next Right node
            result = findBranchSum(node, value); //recursive call using new node
        }
        return(result);
    }
}

What am I doing wrong, and how can I fix my code to find the sum of each branch on the tree?我做错了什么,如何修复我的代码以找到树上每个分支的总和? Thank you in advance.先感谢您。 I apologize for any errors in my format, or missing information.对于格式中的任何错误或信息缺失,我深表歉意。

This is wrong:这是错误的:

if (node->getLeftSide() != nullptr)
{
  node = node->getLeftSide(); //advance to next Left node
  result = findBranchSum(node, value); //recursive call using new node
}
if (node->getRightSide() != nullptr)
{
  node = node->getRightSide(); //advance to next Right node
  result = findBranchSum(node, value); //recursive call using new node
}

because you move to the left and then to the right branch of the left ( node is changed by your assignment), if it exists: Change to:因为你向左移动然后向左移动到右分支( node被你的分配改变),如果它存在:更改为:

if (node->getLeftSide() != nullptr)
{
  result = findBranchSum(node->getLeftSide(), value);
}
if (node->getRightSide() != nullptr)
{
  result = findBranchSum(node->getRightSide(), value);
}

Your return value management is also broken, change it to:你的返回值管理也坏了,改成:

if (node->getLeftSide() != nullptr)
{
  result = findBranchSum(node->getLeftSide(), value);
}
if (!result && node->getRightSide() != nullptr) // cut exploration if previous was correct...
{
  result = findBranchSum(node->getRightSide(), value);
}
return result;

if you need to stop at the first correct branch.如果您需要停在第一个正确的分支。

I might try something like the following.我可能会尝试以下内容。

bool IsLeaf(Node const * node) {
  return node && !node->left && !node->right;
}

bool CheckPathSum(Node const * node, int const target, int const sum_so_far) {
  if (!node) return false;
  int const sum = sum_so_far + node->element;
  if IsLeaf(node) && (sum == target)  return true;
  return CheckPathSum(node->left, target, sum) ||
         CheckPathSum(node->right, target, sum);
}

Call as
CheckPathSum(root, target, 0);

In Java, i tried this-在 Java 中,我试过这个-

private static void branchSumsUtil(TreeNode root, List<Integer> sumArray, int runningSum) {

    if (root == null){
        return;
    }

    int newRunningSum = runningSum + root.key;

    if (root.left == null && root.right == null){
        sumArray.add(newRunningSum);
    }
    branchSumsUtil(root.left, sumArray, newRunningSum);
    branchSumsUtil(root.right, sumArray, newRunningSum);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM