首页 > 代码库 > 求二叉树中任意两个结点的距离

求二叉树中任意两个结点的距离

求二叉树中任意两个结点的距离

实现步骤:

  1. 计算跟到第一个结点的距离;
  2. 计算跟到第二个结点的距离;
  3. 计算lca;
  4. 计算跟到lca结点的距离;
  5. 结果为(1) + (2) - 2 * (4),因为重复计算了两次的从跟到lca结点的距离;

1

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

2

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

test

技术分享

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))

结果为:

Distance between node 4 & 5: 2Distance between node 4 & 6: 4Distance between node 3 & 4: 3Distance between node 2 & 4: 1Distance between node 8 & 5: 5

求二叉树中任意两个结点的距离