Python, LintCode, 88. Lowest Common Ancestor of a Binary Tree

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""


class Solution:
    """
    @param: root: The root of the binary search tree.
    @param: A: A TreeNode in a Binary.
    @param: B: A TreeNode 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
        leftnode = self.lowestCommonAncestor(root.left, A, B)
        rightnode = self.lowestCommonAncestor(root.right, A, B)
        if leftnode != None and rightnode != None:
            return root
        elif leftnode != None:
            return leftnode
        else:
            return rightnode

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章