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 of BST INPUT Binary Search Tree 6 2 p 8 q 0 4 7 9 Input Values: root = [6,2,8,0,4,7,9] p = 2 q = 8 Find LCA of nodes p and q ALGORITHM STEPS Path Comparison Approach 1 Find Path to p Path: 6 --> 2 [6, 2] 2 Find Path to q Path: 6 --> 8 [6, 8] 3 Compare Paths Find common prefix Path p: [6, 2] Path q: [6, 8] Common: 6 (at index 0) 4 Return LCA Last common ancestor LCA = 6 FINAL RESULT LCA Found in BST 6 LCA 2 8 0 4 7 9 OUTPUT 6 Node 6 is the lowest common ancestor [OK] Key Insight: In a BST, if p is in left subtree and q is in right subtree (or vice versa), current node is the LCA. Path comparison finds paths from root to both nodes, then returns the last common node. Time: O(h), Space: O(h) TutorialsPoint - Lowest Common Ancestor of a Binary Search Tree | Path Comparison Approach
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