Python recursive solution 108ms

  • 1

    This solution only works when p and q are in the tree, and for this problem, it seems that's the case.

    class Solution(object):
        def lowestCommonAncestor(self, root, p, q):
            :type root: TreeNode
            :type p: TreeNode
            :type q: TreeNode
            :rtype: TreeNode
            if not root:
                return None
            if p==root or q==root:
                return root
            if p.val>q.val:
            if p.val<root.val and q.val>root.val:
                return root
            if p.val>root.val:
                return self.lowestCommonAncestor(root.right, p, q)
            return self.lowestCommonAncestor(root.left, p, q)

Log in to reply

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