Recursive BST Traversal
Intuition
The BST property gives us a powerful way to find the LCA. If both p and q are smaller than the current node, the LCA must be in the left subtree. If both are greater, the LCA must be in the right subtree. If one is on each side (or one equals the current node), then the current node is the LCA. This works because the BST ordering guarantees that the split point is exactly the lowest common ancestor. We do not need to search the entire tree -- we follow a single path from root to the LCA.
Algorithm
- Start at the root node.
- If both p.val and q.val are less than root.val, recurse into the left subtree.
- If both p.val and q.val are greater than root.val, recurse into the right subtree.
- Otherwise, root is the split point where p and q diverge (or one of them equals root), so return root.
O(h) where h is the height of the treeSpaceO(h) for the recursion stackCode (C++ · Java · Python · Go)
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (p->val < root->val && q->val < root->val) {
return lowestCommonAncestor(root->left, p, q);
}
if (p->val > root->val && q->val > root->val) {
return lowestCommonAncestor(root->right, p, q);
}
return root;
}
};class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (p.val < root.val && q.val < root.val) {
return lowestCommonAncestor(root.left, p, q);
}
if (p.val > root.val && q.val > root.val) {
return lowestCommonAncestor(root.right, p, q);
}
return root;
}
}def lowestCommonAncestor(root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
if p.val < root.val and q.val < root.val:
return lowestCommonAncestor(root.left, p, q)
if p.val > root.val and q.val > root.val:
return lowestCommonAncestor(root.right, p, q)
return rootfunc lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if p.Val < root.Val && q.Val < root.Val {
return lowestCommonAncestor(root.Left, p, q)
}
if p.Val > root.Val && q.Val > root.Val {
return lowestCommonAncestor(root.Right, p, q)
}
return root
}