My recursive python solution


  • 0
    I
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        # @param {TreeNode} root
        # @param {TreeNode} p
        # @param {TreeNode} q
        # @return {TreeNode}
        def lowestCommonAncestor(self, root, p, q):
            if root != None:
                if root.val not in (p.val, q.val):
                    if root.val > p.val and root.val < q.val:
                        return root
                    if root.val < p.val and root.val > q.val:
                        return root
                    if root.val > p.val:
                        return self.lowestCommonAncestor(root.left, p, q)
                    else:
                        return self.lowestCommonAncestor(root.right, p, q)
                else:
                    return root
            else:
                return None

Log in to reply
 

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