- 计算跟到第一个结点的距离;
- 计算跟到第二个结点的距离;
- 计算lca;
- 计算跟到lca结点的距离;
- 结果为(1) + (2) - 2 * (4),因为重复计算了两次的从跟到lca结点的距离;
):
def __init__(self, value=0):
self.value = value
self.left = self.right = None
def get_path_length(root, n, path):
if not root:
return 0
if root.value == n:
return path
else:
return get_path_length(root.left, n, path + 1) or get_path_length(root.right, n, path + 1)
def find_lca(root, n1, n2):
if root is None:
return None
if root.value == n1 or root.value == n2:
return root
left = find_lca(root.left, n1, n2)
right = find_lca(root.right, n1, n2)
if left and right:
return root
elif left:
return left
elif right:
return right
else:
return None
def find_distance(root, n1, n2):
x = get_path_length(root, n1, 0)
y = get_path_length(root, n2, 0)
lca = find_lca(root, n1, n2).value
lca_dis = get_path_length(root, lca, 0)
return (x + y) - 2 * lca_dis
相关文章: