Python Very easy to understand


  • 0
    A
    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def lowestCommonAncestor(self, root, p, q):
            """
            :type root: TreeNode
            :type p: TreeNode
            :type q: TreeNode
            :rtype: TreeNode
            """
            # If root null then return None
            if root == None:
                return None
            # If found any of the node then return value to parent
            if root == p or root == q:
                return root.val
            # go to left and right to find p and q
            left = self.lowestCommonAncestor(root.left, p, q)
            right = self.lowestCommonAncestor(root.right, p, q)
            # if both left and right are not null for given node then this is common Ancestor
            if(left != None and right != None):
                return root.val
            # if both are None then this is not LCA
            if(left == None and right == None):
                return None
            # Either or a
            if(left != None):
                return left
            else:
                return right
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.