Graph Theory37 sections · 1633 units
Open in Course

Walkthrough - Example Tree

(Tracing the recursion)

Consider a tree rooted at 33 with left child 55 and right child 11. Node 55 has children 66 and 22. Node 11 has children 00 and 88. Find LCA(55, 11). Call on root 33. Left subtree returns 55 (found target). Right subtree returns 11 (found target). Both are non-null, so 33 is the LCA.

Now find LCA(55, 44) where 44 is a child of 22. Call on root 33. Left subtree finds 55 first and returns it. But 44 is also in the left subtree under 22. The left call returns 55 (since 55 is encountered before reaching 44's subtree). Right returns null. So 55 is the LCA. Node 55 is an ancestor of 44, confirming the answer.