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

标签 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。我认为问题在于通过引用传递,我无法检测到它...... 它总是给出错误的答案,即使它是真的!

最佳答案

我不确定你想要什么,但我怀疑问题是你修改了 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) )

关于c++在递归中通过引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38479051/

相关文章:

python - Python 中 boolean 表达式的求值

java - 创建一个大小为 1 位的 Java boolean 值

c++ - Metro Windows 8 C++ 应用程序可以包含内联汇编器吗?

c++ - 如何在 CMake 中使用对象库创建共享库

c++ - 与阅读不同格式的数字字符有关的问题

c++ - 为什么每次使用 std::random_device 和 mingw gcc4.8.1 运行都会得到相同的序列?

C++ 线程构造函数,使用 new(object) 会造成内存泄漏

c++ - 初始化一次标志?

android - boolean 值从一开始就设置为 true

C++:全局变量与局部变量。用什么?