LeetCode笔记

最近公共祖先

2018-03-20  本文已影响3人  只为此心无垠

LeetCode题目地址

在root为根的二叉树中找A,B的LCA:

def lowestCommonAncestor(self, root, A, B):
        # write your code here
        
        if root is None:
            return None
            
        if root is A or root is B:
            return root
        #分   
        left = self.lowestCommonAncestor(root.left, A, B)
        right = self.lowestCommonAncestor(root.right, A, B)
        #治
        if left is not None and right is not None:
            return root
        if left is not None:
            return left
        if right is not None:
            return right
        return None
上一篇 下一篇

猜你喜欢

热点阅读