Lowest Common Ancestor III
Master this topic with zero to advance depth.
Lowest Common Ancestor III
With parent pointers.
Level I: Set of Ancestors
Intuition
Since each node has a parent pointer, we can trace the path from node p back to the root, storing all ancestors in a Hash Set. Then, trace back from node q. The first ancestor of q that is already in the set is the LCA.
Thought Process
- Traverse from
pto root, adding every node toSet. - Traverse from
qto root. - Return first node found in
Set.
Detailed Dry Run
| Node | Set (Ancestors of P) | In Set? |
|---|---|---|
| P=5 | {5} | - |
| 3 (parent of 5) | {5, 3} | - |
| Q=1 | {5, 3} | NO |
| 3 (parent of 1) | {5, 3} | YES! (Result=3) |
Level II: Depth Alignment
Intuition
We can calculate the depth of both nodes p and q. Then, move the deeper node up its parent chain until both nodes are at the same depth. From there, move both up together until they meet.
Logic
- Calculate
depthPanddepthQ. - Align depths by moving up parent pointers.
- Move both until
p == q.
Detailed Dry Run
P at depth 3, Q at depth 2. Move P up once. Both at depth 2. Move together -> meet at LCA.
Level III: Optimal (Two Pointers / Intersection)
Intuition
Thought Process
This problem is equivalent to finding the intersection of two linked lists. We use two pointers, a and b.
- Pointer
astarts atp,bstarts atq. - When a pointer reaches the root (
null), it jumps to the other starting node (qorp). - They will eventually meet at the intersection point (the LCA) after at most steps.
Logic
a = (a == null) ? q : a.parent
b = (b == null) ? p : b.parent
Detailed Dry Run
| Step | Ptr A | Ptr B | Notes |
|---|---|---|---|
| 1 | 5 | 1 | Start |
| 2 | 3 | 3 | MEET! (LCA=3) |
⚠️ Common Pitfalls & Tips
Be extremely careful with the null jumping logic. If you jump at the wrong node, you might enter an infinite loop. The pointers must switch to the other starting node to align their path lengths.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.