gpt4 book ai didi

python - 如何递归地找到二叉树中节点的高度

转载 作者:太空狗 更新时间:2023-10-30 00:20:47 25 4
gpt4 key购买 nike

path = 0 # the lenght of the path
while self.right != None or self.left != None:
while self.right != None:
self = self.right
path = path +1
while self.left != None:
self = self.left
path = path +1
return path

这是我查找高度的示例代码,定义为从自身到叶子的节点数的最长路径。叶子节点的高度为1。

这是行不通的。

最佳答案

您所做的不是递归的,而是迭代的。递归是这样的:

def height(node):
if node is None:
return 0
else:
return max(height(node.left), height(node.right)) + 1

关于python - 如何递归地找到二叉树中节点的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13322616/

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