找不到合适的标题,请原谅我
我正在尝试分析BST的递归函数,该函数返回1。
经过错误的计算后,我得到的返回值为0,我想了解我在这里做错了什么。
我们从这样调用函数main.c
:func_3(root, 9);
所以总和= 9
这是代码块:
int func_3(struct node* node, int sum)
{
if (node == NULL)
return(sum == 0);
else
{
int subSum = sum - node->data;
return (func_3(node->left, subSum) || func_3(node->right, subSum));
}
}
我的计算: func(5,9)-> func3(3,4)-> func(1,1)->返回subTree = sum = 0。
1
如果存在(root node
到a的leaf node
)值总和等于的路径,则此函数返回sum
。
In your function call func_3(root, 9)
in main, what you are trying to do is check if there is any path in your binary tree, such that the sum of values of all the nodes in that path is equal to 9.
There is such path, which is the leftmost path (5->3->1), so your function will return 1.
This is how it is returning 1. First call is
func_3(node, 9)
where node
is pointing to root node of this tree, i.e. root node with value 5
.
Here node is not null. So,
subSum = 9 - 5 = 4.
Next call is
func3(node, 4)
where node
is pointing to node with value 3
(left child of node of previous call)
Here again node is not null, So,
subSum = 4 - 3 = 1
Next call is
func3(node, 1)
where node
is pointing to node with value 1
(left child of node of previous call)
Here again node is not null, So,
subSum = 1 - 1 = 0
Next call is
func_3(node, 0)
where node
is pointing to NULL
(left child of node of previous call)
不过这一次node
是NULL
,既然sum == 0
是真实的,它会返回1
,而这个返回值将返回所有的方式递归终于到main
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句