The Lowest Common Ancestor (LCA) of two nodes p and q in a BST is the deepest node that has both p and q as descendants (a node can be a descendant of itself).
In a BST, the LCA is the split point where p and q diverge to different subtrees:
The BST property makes this O(h) instead of O(n) for a general binary tree. Elegant!
lowest_common_ancestor(root, 2, 8)
6
lowest_common_ancestor(root, 2, 4)
2
lowest_common_ancestor(root, 3, 5)
4