c ++在递归中通过引用传递

时间:2016-07-20 10:43:12

标签: c++ c++11 boolean binary-tree pass-by-reference

bool roottoleafsumequaltox(BinaryTreenode<int>* root, int &x)
{
    if(root == NULL)
    {
        return (x==0);
    }
    else
    {
     bool ans = false;
     x = x - root->data;

     if(x == 0 && root->left == NULL && root->right == NULL)
     {
       return true;
     }

     if(root->left)
      ans = ans || roottoleafsumequaltox(root->left, x);

     if(root->right)
      ans = ans || roottoleafsumequaltox(root->right, x);

     return ans;
   }
}

必须返回根到叶总和是否等于给定数x。我认为问题在于通过引用传递,我无法检测到它... 它总是给出错误的答案,即使它是真的!

2 个答案:

答案 0 :(得分:1)

我不确定你想要什么,但我怀疑问题是你修改了x

x= x- root->data;

所以,当您将x传递给roottoleafsumequaltox()

ans= ans || roottoleafsumequaltox(root->left, x);
ans = ans || roottoleafsumequaltox(root->right, x);

您传递的x带有修改后的值

我想您可以避免修改x并以这种方式编写if

if( (x == root->data) && (root->left == nullptr) && (root->right == nullptr) )

答案 1 :(得分:1)

是的,问题在于通过引用传递。 x值随着每个节点遍历而不断减少。

摆脱引用传递,然后更新:

roottoleafsumequaltox(root->left/right, (x - root->data)) 

并查看 (leaf_node->data == x)

如果您已经发现从root(或任何其他节点)到leaf的路由之一,那么为了优化,您也不会去检查正确的子树。 sum == x在该位置)。