gpt4 book ai didi

algorithm - 使用递归在二叉树中根和节点之间的距离

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:22:12 26 4
gpt4 key购买 nike

我读了一个算法来查找二叉树中两个节点之间的距离。在从根到节点的那个距离中,需要给定节点的最低共同祖先。
这段代码在二叉树中查找(1 + 从根到给定节点的距离)。

 int Pathlength(Node* root, int n1) {
if (root != NULL) {
int x=0;
if ((root->data == n1) || (x=Pathlength(root->left, n1))>0||(x=Pathlength(root->right, n1))>0)
{

return x + 1;
}
return 0;
}
return 0;
}

我不明白的是'x'有两个值,一个来自左子树,另一个来自右子树,它怎么知道返回哪个值?
例如,如果树是这样的:

20  
/ \
8 2

然后调用 Pathlength(root, 8),

x=Pathlength(root->left,8)=1  
x=Pathlength(root->right,2)=0

那么,在语句“return x+1”中,它如何返回正确的 x 值?

最佳答案

你需要了解在C/C++中,逻辑或||是短路的:

当评估A || B,如果 A 为 True,则不评估 B(因为无论 B 是什么,A||B 始终为 True)。

在这个表达式中:

(root->data == n1) || (x=Pathlength(root->left, n1))>0||(x=Pathlength(root->right, n1))>0

由于 Pathlength(root->left, n1) 为 1,因此它被分配给 x,并且 x>0 计算为 True,x=Pathlength (root->right, n1) 不再被调用。

关于algorithm - 使用递归在二叉树中根和节点之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32295503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com