【发布时间】:2020-03-23 18:28:12
【问题描述】:
这个递归是如何进行的?第一次是 14-10=4 和 if (node->left) 条件满足所以使用 node->left(node 8) 和 sum value(4) 的函数被调用,但是在 node->left 和 node->right 中 or 条件的用途是什么?
假设给定的总和是 21,那么在我们最后递归节点 3 并在 node->left 函数中调用 sum=3 后,1 作为 sum=0 返回,并且没有子节点,但是 1 返回的位置到节点 8,然后我们去节点 5?
如果我们做节点 5 不返回任何值,那么它如何计算返回 1 的左孩子,而它的右孩子不返回任何值?我看不到实际在哪里使用 or 条件,为什么在 node->left 和 node->right if 条件下都需要使用它?
int main()
{
int sum=14; //sum=21;
struct node *root = newnode(10);
root->left = newnode(8);
root->right = newnode(2);
root->left->left = newnode(3);
root->left->right = newnode(5);
root->right->left = newnode(2);
if(hasPathSum(root, sum))
printf("There is a root-to-leaf path with sum %d", sum);
else
printf("There is no root-to-leaf path with sum %d", sum);
getchar();
return 0;
}
bool hasPathSum(struct node* node, int sum)
{
/* return true if we run out of tree and sum==0 */
if (node == NULL)
{
return (sum == 0);
}
else
{
bool ans = 0;
int subSum = sum - node->data;
if ( subSum == 0 && node->left == NULL && node->right == NULL )
return 1;
if(node->left)
ans = ans || hasPathSum(node->left, subSum);
if(node->right)
ans = ans || hasPathSum(node->right, subSum);
return ans;
}
}
【问题讨论】:
标签: c binary-tree