โ† Trees, Graphs & DP
#6 most askedVery commonMediumBST

Lowest Common Ancestor of a BST

New to BST? Learn it from scratch first
Binary Search Trees in Depth โ†’
๐Ÿข Asked in real interviews
No reports yet. Were you asked this? Be the first to say where.
I was asked this

In a BST, return the value of the lowest node that has both p and q (values) as descendants. A node counts as its own descendant.

BST [6, 2, 8, 0, 4, 7, 9], p = 2, q = 8 โ†’ 6; p = 2, q = 4 โ†’ 2.

๐Ÿงช Practice

Write your solution, then press Run tests. Explain your approach out loud as you go.

Python
def lca_bst(root, p, q):
    pass

Output appears here. Press Run or Ctrl/โŒ˜ + Enter.

Try it first. Struggling for a few minutes is how it sticks.