Python支持多个返回值,因此您不需要像C或C ++中那样的指针参数。这是代码的翻译:
def diameter_height(node):
if node is None:
return 0, 0
ld, lh = diameter_height(node.left)
rd, rh = diameter_height(node.right)
return max(lh + rh + 1, ld, rd), 1 + max(lh, rh)
def find_tree_diameter(node):
d, _ = diameter_height(node)
return d
该函数diameter_height
返回树的直径和高度,并find_tree_diameter
使用它仅计算直径(通过丢弃高度)。