Solutions
1. Brute Force
O(n²) time | O(1) space
Intuition
We can take every ancestor of p and check it against every ancestor of q with two nested loops.
Algorithm
- Traverse through all the ancestors of
p. - For each step, traverse through all the ancestors of
qand return the first common node.
Code
2. Hash Table
O(n) time | O(n) space
Intuition
We can first traverse through all the ancestors of p and put them into a hash set.
Then traverse through all the ancestors of q and return the first one that is in the hash set.
Algorithm
- Create an empty hash set.
- Traverse through all the ancestors of
p, adding every ancestor to the hash set. - Traverse through all the ancestors of
qand return the first one that is in the hash set.
Code
3. Depth Alignment
O(n) time | O(1) space
Intuition
If both nodes were at the same depth, we could traverse both nodes' ancestors at the same time with one loop and they would meet at the lowest common ancestor.
To align the depths, we can count each depth first and move the deeper node up by the difference.
Algorithm
- Traverse through all the ancestors of
p, counting the steps intop_depth. - Traverse through all the ancestors of
q, counting the steps intoq_depth. - Move the deeper node up by the difference between
p_depthandq_depth, so both of them start at the same depth. - Traverse through both nodes' ancestors at the same time until they meet.
- Return the node both of them are on.
Code
4. Two Pointers
O(n) time | O(1) space
Intuition
We can traverse both nodes' ancestors at the same time with one loop.
When the pointer of p's ancestors reaches the root, we put it on q, and when the pointer of q's ancestors reaches the root, we put it on p.
Then both pointers go through the same number of steps (depth of p + depth of q), so they meet at the lowest common ancestor.
Algorithm
- Create
current_pandcurrent_qpointer variables withpandqas initial values. - Traverse through both nodes' ancestors at the same time while
current_pandcurrent_qare not the same node.- Move
current_pto its parent, or toqifcurrent_pis the root. - Move
current_qto its parent, or topifcurrent_qis the root.
- Move
- Return
current_p.
Code
# Definitions:# class TreeNodeWithParent:# def __init__(self, val=0, children=None):# self.val = val# self.children = children if children is not None else []# self.parent = None def lowestCommonAncestor(p: TreeNodeWithParent, q: TreeNodeWithParent) -> TreeNodeWithParent: pass Press Visualise to step through your code.