1. Recursive BST Invariant Search
Recursively descend left when both targets are smaller than root, right when both are larger, or return root as soon as paths diverge.
Explores at most one node per level down to height h.
Call stack frames scale with tree height h (O(log n) balanced, O(n) skewed).
How It Works
Recursive Branch Pruning
Using the BST ordering invariant recursively mirrors binary search:
- If
p.val < root.val && q.val < root.val: recurse onroot.left. - Else if
p.val > root.val && q.val > root.val: recurse onroot.right. - Otherwise return
root(paths split here orrootequalsporq).
Step-by-Step Dry Run
Both 2 < 6 and 4 < 6 hold, so recurse strictly into left subtree rooted at 2.
call LCA(node 2)- +Clean 6-line recursive expression
- +Natural BST divide-and-conquer formulation
- -Consumes O(h) recursion stack frames instead of O(1) space
Reference Implementation
Complete implementation for Recursive BST Invariant Search in Python, JavaScript, Java, C++, and C.
def lowest_common_ancestor_rec(root, p, q):if p.val < root.val and q.val < root.val:return lowest_common_ancestor_rec(root.left, p, q)if p.val > root.val and q.val > root.val:return lowest_common_ancestor_rec(root.right, p, q)return root
function lowestCommonAncestorRec(root, p, q) {
if (p.val < root.val && q.val < root.val) {
return lowestCommonAncestorRec(root.left, p, q);
}
if (p.val > root.val && q.val > root.val) {
return lowestCommonAncestorRec(root.right, p, q);
}
return root;
}public class Solution {
static class TreeNode { int val; TreeNode left, right; }
public static TreeNode lowestCommonAncestorRec(TreeNode root, TreeNode p, TreeNode q) {
if (p.val < root.val && q.val < root.val) {
return lowestCommonAncestorRec(root.left, p, q);
}
if (p.val > root.val && q.val > root.val) {
return lowestCommonAncestorRec(root.right, p, q);
}
return root;
}
}struct TreeNode { int val; TreeNode *left, *right; };
TreeNode* lowestCommonAncestorRec(TreeNode* root, TreeNode* p, TreeNode* q) {
if (p->val < root->val && q->val < root->val) {
return lowestCommonAncestorRec(root->left, p, q);
}
if (p->val > root->val && q->val > root->val) {
return lowestCommonAncestorRec(root->right, p, q);
}
return root;
}struct TreeNode { int val; struct TreeNode *left, *right; };
struct TreeNode* lowestCommonAncestorRec(struct TreeNode* root, struct TreeNode* p, struct TreeNode* q) {
if (p->val < root->val && q->val < root->val) {
return lowestCommonAncestorRec(root->left, p, q);
}
if (p->val > root->val && q->val > root->val) {
return lowestCommonAncestorRec(root->right, p, q);
}
return root;
}