Trees and binary search trees · Exercise 32 of 100
Lowest common ancestor
An ancestor lies on the path from the root to a node, and a node counts as its own ancestor. When both target nodes are present, trace their paths from the root and take the last node those paths share. It is the deepest ancestor of both targets.
Try it yourself
Root 30 has children 18 and 40. Node 18 has children 4 and 25. Node 9 is a child of 4, and node 22 is a child of 25. What is the value of the lowest common ancestor of 9 and 22?
One-step hint
Write the paths from the root to 9 and to 22 on separate lines. Compare them until the paths split.
Worked solution
- The path to 9 goes through 30, 18, and 4. The path to 22 goes through 30, 18, and 25.
- The paths share 30 and 18, then take different child links from 18. Their last shared node is 18.