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/