Lowest Common Ancestor of a Binary Search Tree - Problem

Given a Binary Search Tree (BST), find the lowest common ancestor (LCA) node of two given nodes p and q in the BST.

The lowest common ancestor is defined as the lowest node in the tree that has both p and q as descendants. Note that a node can be a descendant of itself.

๐ŸŒณ Key Insight: In a BST, all nodes in the left subtree are smaller than the root, and all nodes in the right subtree are larger. This property makes finding the LCA much more efficient than in a regular binary tree!

Example: If we have nodes with values 2 and 8 in a BST, and the root is 6, then 6 is their LCA because 2 < 6 < 8, meaning they diverge at node 6.

Input & Output

example_1.py โ€” Basic LCA
$ Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
โ€บ Output: 6
๐Ÿ’ก Note: The LCA of nodes 2 and 8 is 6, since 2 < 6 < 8, making 6 the split point where their paths diverge.
example_2.py โ€” LCA with ancestor relationship
$ Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
โ€บ Output: 2
๐Ÿ’ก Note: The LCA of nodes 2 and 4 is 2, since node 2 is an ancestor of node 4 (and a node can be an ancestor of itself).
example_3.py โ€” Simple tree
$ Input: root = [2,1,3], p = 1, q = 3
โ€บ Output: 2
๐Ÿ’ก Note: The LCA of nodes 1 and 3 is 2, since 1 < 2 < 3, making 2 the root where paths to both nodes split.

Constraints

  • The number of nodes in the tree is in the range [2, 105]
  • -109 โ‰ค Node.val โ‰ค 109
  • All Node.val are unique
  • p โ‰  q
  • Both p and q will exist in the BST

Visualization

Tap to expand
6280479Looking for nodes 4 and 74 < 6 and 7 > 6Split point found at 6!Time: O(h), Space: O(1)
Understanding the Visualization
1
Start at Peak
Begin at the root of the BST
2
Check Direction
Compare both targets with current elevation
3
Navigate Smart
Go left if both lower, right if both higher
4
Find Split
When targets are on different sides, you found the junction
Key Takeaway
๐ŸŽฏ Key Insight: In a BST, the LCA is the first node where the paths to p and q diverge - when one target is โ‰ค current node and the other is โ‰ฅ current node.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28 Apple 22
89.5K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen