标签:获取 ext sans section over find bre main http
class Node(object):
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
def get_path_length(root, path, k):
# base case handling
if root is None:
return False
path.append(root.value)
if root.value == k:
return True
if ((root.left != None and get_path_length(root.left, path, k)) or
(root.right != None and get_path_length(root.right, path, k))):
return True
# 如果当前结点的值并不是k
path.pop()
return False
def find_distance(root, n1, n2):
if root:
# 获取第一个结点的路径(存储跟结点到i)
path1 = []
get_path_length(root, path1, n1)
# 获取第二个结点的路径
path2 = []
get_path_length(root, path2, n2)
# 找到它们的公共祖先
i = 0
while i < len(path1) and i < len(path2):
if path1[i] != path2[i]:
break
i = i + 1
# 减去重复计算的跟结点到lca部分即为结果
return (len(path1) + len(path2) - 2 * i)
else:
return 0
if __name__ == ‘__main__‘:
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.right.right = Node(7)
root.right.left = Node(6)
root.left.right = Node(5)
root.right.left.right = Node(8)
dist = find_distance(root, 4, 5)
print("Distance between node {} & {}: {}".format(4, 5, dist))
dist = find_distance(root, 4, 6)
print("Distance between node {} & {}: {}".format(4, 6, dist))
dist = find_distance(root, 3, 4)
print("Distance between node {} & {}: {}".format(3, 4, dist))
dist = find_distance(root, 2, 4)
print("Distance between node {} & {}: {}".format(2, 4, dist))
dist = find_distance(root, 8, 5)
print("Distance between node {} & {}: {}".format(8, 5, dist))
标签:获取 ext sans section over find bre main http
原文地址:http://www.cnblogs.com/George1994/p/7348499.html