【问题标题】:c++ passing by reference in recursionc++ 在递归中通过引用传递
【发布时间】:2016-07-20 10:43:12
【问题描述】:
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。我认为问题在于通过引用传递,我无法检测到它...... 它总是给出错误的答案,即使它是真的!

【问题讨论】:

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


    【解决方案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) )
    

    【讨论】:

      【解决方案2】:

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

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

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

      并检查 (leaf_node-&gt;data == x)

      确保,为了优化,如果您已经发现从根(或任何其他节点)到叶子的路径之一给出 sum = = x(在那个位置)。

      【讨论】:

        猜你喜欢
        • 2011-05-02
        • 2012-10-10
        • 2016-04-09
        • 2019-01-28
        • 1970-01-01
        • 2020-10-02
        • 2011-12-12
        • 1970-01-01
        • 2011-01-14
        相关资源
        最近更新 更多