二叉树节点间的最大距离问题
求二叉树两节点间的最大距离(可能过根节点,也可能不过),LeetCode 543
思路
最大距离可能来自三种情况:
- 根节点左子树上的最大距离
- 根节点右子树上的最大距离
- 左孩子最大深度ldepth,到根节点,到右孩子最大深度rdepth
实现1
def max_distance(self):
def post_order(node):
if node is None:
record[0] = 0
return 0
lmax = post_order(node.left)
max_from_left = record[0]
rmax = post_order(node.right)
max_from_right = record[0]
cur_max = max_from_left + max_from_right + 1
record[0] = max(max_from_left, max_from_right) + 1
return max(max(lmax, rmax), cur_max)
if not self.root:
return 0
record = [0]
return post_order(self.root) - 1
实现2
def max_distance2(self):
def depth(node):
if not node:
return 0
ldepth = depth(node.left)
rdepth = depth(node.right)
result[0] = max(result[0], ldepth+rdepth+1)
return max(ldepth, rdepth)+1
result = [0]
depth(self.root)
return result[0] - 1
实现3
def max_distance3(self):
def depth(node):
nonlocal result
if not node:
return 0
ldepth = depth(node.left)
rdepth = depth(node.right)
result = max(result, ldepth+rdepth+1)
return max(ldepth, rdepth)+1
result = 0
depth(self.root)
return result - 1
测试
来源:CSDN
作者:孤舟钓客
链接:https://blog.csdn.net/guzhou_diaoke/article/details/103570296