Skip to content

Latest commit

 

History

History
24 lines (22 loc) · 877 Bytes

236.md

File metadata and controls

24 lines (22 loc) · 877 Bytes

236. Lowest Common Ancestor of a Binary Tree

给定一棵二叉树,寻找其中两个给定节点的最近公共祖先(LCA)。

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """
        # 6 star, no idea
        # 递归解决,向左右子树递归查找,直到找到p或q, 此时left和right的值有两种情况,一种是一个是lca一个是None, 另一种是分别是p和q
        # 这个代码太简洁了,还得好好消化
        if not root or root in (p, q):
            return root
        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)
        if left and right:
            return root
        return left or right