SDE & MLE Prep

235. Lowest Common Ancestor of a Binary Search Tree

Problem

Given a binary search tree and two of its nodes p and q, return their lowest common ancestor: the deepest node that has both as descendants (a node counts as its own descendant).

Example: [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 → 6; p = 2, q = 4 → 2

Use BST ordering: if both p, q are smaller go left, both larger go right; otherwise the current node splits them → LCA.

Complexity: O(h) time, O(1) space.

class Solution:
    def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
        while root:
            if p.val < root.val and q.val < root.val:
                root = root.left
            elif p.val > root.val and q.val > root.val:
                root = root.right
            else:
                return root