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