lintcode练习 - 88. Lowest Common Ancestor of a Binary Tree

版权声明:原创部分都是自己总结的,如果转载请指明出处。觉得有帮助的老铁,请双击666! https://blog.csdn.net/qq_36387683/article/details/82530160

88. Lowest Common Ancestor of a Binary Tree

给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。

最近公共祖先是两个节点的公共的祖先节点且具有最大深度。

样例

对于下面这棵二叉树

  4
 / \
3   7
   / \
  5   6

LCA(3, 5) = 4

LCA(5, 6) = 7

LCA(6, 7) = 7

注意事项

假设给出的两个节点都在树中存在

解题思路:

def lowestCommonAncestor(self, root, A, B):
        # write your code here
        if root is None:
            return None
        #找到A或者B,就返回该节点 
        if root is A or root is B:
            return root
        left = self.lowestCommonAncestor(root.left, A, B)
        right = self.lowestCommonAncestor(root.right, A, B)
        #如果左节点也找到了,右节点也找到了,则root是AB的公共节点
        if left is not None and right is not None:
            return root
        #其中一个节点没找到,如果left不为空,则left是AB的公共节点
        if left is not None:
            return left
        #同上
        if right is not None:
            return right
        return None

猜你喜欢

转载自blog.csdn.net/qq_36387683/article/details/82530160