Problem
Given values of two nodes in a Binary Tree p
and q
, find the Lowest Common Ancestor (LCA).
It may be assumed that both nodes exist in the tree and Node has parent pointer.
|
|
Definition
Lowest Common Ancestor Definition
Examples
Example 1:
graph TD; 6; 6 --- 2; 6 --- 8; 2 --- 0; 2 --- 4; 8 --- 7; 8 --- 9; 4 --- 3; 4 --- 5; style 2 fill:#FF9933 style 8 fill:#FF9933 style 6 fill:#3399FF
|
|
Example 2:
graph TD; 6; 6 --- 2; 6 --- 8; 2 --- 0; 2 --- 4; 8 --- 7; 8 --- 9; 4 --- 3; 4 --- 5; style 2 fill:#FF9933 style 4 fill:#FF9933 style 2 fill:#3399FF
|
|
Solution
Method 1 - Using Hashtable to create ancestor set
Algorithm
- Create an hashset for node p, traversing till
root
node - Check if
q
or any of its ancestors exist in hashset, if yes return the first existing ancestor.
Code
|
|
Complexity
- ⏰ Time complexity:
O(h)
- 🧺 Space complexity:
O(h)
Method 2 - Calculate Height Difference Between 2 Nodes
We may have 2 cases for nodes p
and q
:
- Both
p
andq
are at same level ⇨ there is no height difference - They are not at same level ⇨ they have height difference
We can solve the problem in O(1) extra space using following fact :
- Case 1 - Same level - If both nodes are at same level and if we traverse up using parent pointers of both nodes, the first common node in the path to root is LCA.
- Case 2 - Different level - But if they are at different level, then we move up the deeper node pointer by the depth-difference. Once both nodes reach same level, it becomes like case 1, and we traverse them up and return the first common node.
|
|
Complexity
- ⏰ Time complexity:
O(h)
- 🧺 Space complexity:
O(1)
Method 3 - Using Y Shaped Linked List Thinking
We have already seen the problem - Y shaped linked list
For eg. Look at LCA of the Trees here:
Now the challenge is height difference. (Similar challenge we had for in Linked list with length difference.).
Code
|
|