235. Lowest Common Ancestor of a Binary Search Tree
Problem
Given a binary search tree and two of its nodes p and q, return their lowest common ancestor: the deepest node that has both as descendants (a node counts as its own descendant).
Example: [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 → 6; p = 2, q = 4 → 2
Use BST ordering: if both p, q are smaller go left, both larger go right; otherwise the current node splits them → LCA.
Complexity: O(h) time, O(1) space.
class Solution:
def lowestCommonAncestor(self, root: TreeNode, p: TreeNode, q: TreeNode) -> TreeNode:
while root:
if p.val < root.val and q.val < root.val:
root = root.left
elif p.val > root.val and q.val > root.val:
root = root.right
else:
return root
t = make_tree([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5])
assert Solution().lowestCommonAncestor(t, find_node(t, 2), find_node(t, 8)).val == 6
assert Solution().lowestCommonAncestor(t, find_node(t, 2), find_node(t, 4)).val == 2
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while (root != null) {
if (p.val < root.val && q.val < root.val) root = root.left;
else if (p.val > root.val && q.val > root.val) root = root.right;
else return root;
}
return null;
}
}
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
for root != nil {
switch {
case p.Val < root.Val && q.Val < root.Val:
root = root.Left
case p.Val > root.Val && q.Val > root.Val:
root = root.Right
default: // p and q split here (or one of them is root)
return root
}
}
return nil
}