Tensorum
LeetCode 235 · BST

Lowest Common Ancestor of a Binary Search Tree

LeetCode 235 · Medium · solution, intuition & step-by-step walkthrough

Walk down until p and q split.

MediumTreeDepth-First SearchBinary Search TreeBinary TreeBinary Lifting
59 msruntime · beats 92%
59.1 MBmemory · beats 100%
1approach
10accepted runs · last 26 Jun 2024

This is how I solved Lowest Common Ancestor of a Binary Search Tree (LeetCode 235), a medium problem from the BST pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

In a BST, if both p and q are smaller than the current node, their common ancestor is on the left; if both are larger, it's on the right. Otherwise they split here (or one of them is here), so this node is the answer.

Approach

  1. 1

    Current is p or q → return it.

  2. 2

    Both smaller → go left.

  3. 3

    Both larger → go right.

  4. 4

    Otherwise → current node.

How I solved it

BST descentPythonO(h) time
class Solution:
    def lowestCommonAncestor(self, root, p, q):
        if root == p or root == q:
            return root
        cur = root.val
        if cur > p.val and cur > q.val:
            return self.lowestCommonAncestor(root.left, p, q)
        elif cur < p.val and cur < q.val:
            return self.lowestCommonAncestor(root.right, p, q)
        return root
Loading the step-through…

Lowest Common Ancestor of a Binary Search Tree — FAQ

What is the intuition behind Lowest Common Ancestor of a Binary Search Tree?

In a BST, if both p and q are smaller than the current node, their common ancestor is on the left; if both are larger, it's on the right. Otherwise they split here (or one of them is here), so this node is the answer.

How do you solve Lowest Common Ancestor of a Binary Search Tree (LeetCode 235)?

1. Current is p or q → return it. 2. Both smaller → go left. 3. Both larger → go right. 4. Otherwise → current node.

What is the time and space complexity of Lowest Common Ancestor of a Binary Search Tree?

Time: O(h). Space: O(h) recursion. (Accepted approach: BST descent.)

What are common mistakes in Lowest Common Ancestor of a Binary Search Tree?

An iterative loop uses O(1) space.