Finding the Lowest Common Ancestor by Hand
For two vertices in a rooted tree, their lowest common ancestor is the deepest vertex belonging to both parent chains.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Trace a small fork
If B and C are children of A and D is a child of B, ancestors including self for D are D, B, A. For C they are C, A. The deepest common one is A. See parent chains and depth.
Check an ancestor case
The lowest common ancestor of B and D is B because B counts as its own ancestor for this query. Test that case as well as distinct branches. Boundary tests can cover equality of the two queried vertices.[1]
Bring both vertices to the same depth first
In a tree rooted at R, let A and B be children of R, with C below A and D below C. To find the lowest common ancestor of D and A, raise D two steps to A. The first aligned pair is already equal. See parent, child and depth.
Depths: R0, A1, B1, C2, D3
LCA(D,A): D→C→A, result A
LCA(D,B): lift D to A, then A and B both lift to R
Check that a vertex may be an ancestor of itself
The LCA of C and C is C. A pair in distinct trees has no common ancestor unless the model augments the forest with a synthetic root. Test those cases and a pair in opposite branches.