求二叉樹中任意兩個結點的距離


求二叉樹中任意兩個結點的距離

實現步驟:

  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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM