Likou-236 The nearest common ancestor of the binary tree

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root is None:
            return None
        path = []
        path_dict = {
    
    }
        # 记录当前点经历过的路径,重点
        def PreOrder(root, path):
            path.append(root)
            path_dict[root.val] = path
            if root.left:
                PreOrder(root.left, path[:])
            if root.right:
                PreOrder(root.right, path[:])
        PreOrder(root, path)
        p_path = path_dict[p.val]
        q_path = path_dict[q.val]
        # print(p_path)
        # print(q_path)
        res = 0
        # 根据已知路径,找到最近公共祖先
        for parents in zip(p_path, q_path):
            p_parent,q_parent = parents
            if p_parent.val == q_parent.val:
                res = p_parent
        return res

Guess you like

Origin blog.csdn.net/tailonh/article/details/113378924