LintCode:最近公共祖先

来源:互联网 发布:php.ini设置文件大小 编辑:程序博客网 时间:2024/06/06 10:05

LintCode:最近公共祖先

"""Definition of TreeNode:class TreeNode:    def __init__(self, val):        self.val = val        self.left, self.right = None, None"""import copyclass Solution:    """    @param root: The root of the binary search tree.    @param A and B: two nodes in a Binary.    @return: Return the least common ancestor(LCA) of the two nodes.    """     def lowestCommonAncestor(self, root, A, B):        # write your code here        if root == None:            return None        if root == A or root == B:            return root        left = self.lowestCommonAncestor(root.left, A, B)        right = self.lowestCommonAncestor(root.right, A, B)        if left and right:            return root        elif left:            return left        elif right:            return right        else:            return None
0 0