Lowest Common Ancestor of a Binary Search Tree

Walk down — go right if both values exceed node, left if both are less; otherwise current is the LCA.

Medium
Time O(h) Space O(1)
LeetCode
3 min read
tree bst

Problem#

Given a BST and two values p and q (both present), return their lowest common ancestor.

Examples#

  • root=[6,2,8,0,4,7,9,null,null,3,5], p=2, q=86.
  • root=[6,2,8,0,4,7,9,null,null,3,5], p=2, q=42.

Constraints#

  • All node values are unique.

Approach#

If both p and q are greater than the current node, recurse right; if both less, recurse left; otherwise the current node is the LCA.

Solution#

LCA of BST
struct TreeNode { int val; TreeNode* left; TreeNode* right; };
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while (root) {
if (p->val > root->val && q->val > root->val) root = root->right;
else if (p->val < root->val && q->val < root->val) root = root->left;
else return root;
}
return nullptr;
}
};

Editorial#

The BST property fully determines the LCA’s location: it’s the first node where p and q straddle (one on each side, or one equals it). Iterative walk is O(1) space, ideal here.

Complexity#

  • Time: O(h).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.