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 in the BST.

According to the definition of LCA: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."

Key Properties:

  • All nodes in the left subtree have values less than the root
  • All nodes in the right subtree have values greater than the root
  • We can use these properties to efficiently navigate the tree

Input & Output

Example 1 — Different Subtrees
$ Input: root = [6,2,8,0,4,7,9], p = 2, q = 8
Output: 6
💡 Note: The LCA of nodes 2 and 8 is 6. Node 2 is in the left subtree and node 8 is in the right subtree of node 6, making 6 the lowest common ancestor.
Example 2 — Same Subtree
$ Input: root = [6,2,8,0,4,7,9], p = 2, q = 4
Output: 2
💡 Note: The LCA of nodes 2 and 4 is 2. Since node 4 is a descendant of node 2, and we allow a node to be a descendant of itself, the LCA is 2.
Example 3 — Root as LCA
$ Input: root = [2,1,3], p = 1, q = 3
Output: 2
💡 Note: The LCA of nodes 1 and 3 is 2. Node 1 is in the left subtree and node 3 is in the right subtree, so root 2 is their lowest common ancestor.

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
  • p and q will exist in the BST

Visualization

Tap to expand
Lowest Common Ancestor: Find LCA of nodes 2 and 86280479LCA(2, 8) = 6
Understanding the Visualization
1
Input
BST with nodes and two target values p=2, q=8
2
Process
Navigate using BST property: compare targets with current node
3
Output
Return the value of the lowest common ancestor
Key Takeaway
🎯 Key Insight: Use BST ordering property - when targets are on different sides of current node, you've found the LCA
Asked in
Amazon 45 Microsoft 38 Google 35 Facebook 28
156.0K 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