Lowest Common Ancestor in a Binary Tree using Parent Pointer
Given values of two nodes in a Binary Tree, find the Lowest Common Ancestor (LCA). It may be assumed that both nodes exist in the tree.
For example, consider the Binary Tree in diagram, LCA of 10 and 14 is 12 and LCA of 8 and 14 is 8.
Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself). Source : Wikipedia.
We have discussed different approaches to find LCA in set 1. Finding LCA becomes easy when parent pointer is given as we can easily find all ancestors of a node using parent pointer. Below are steps to find LCA.
- Create an empty hash table.
- Insert n1 and all of its ancestors in hash table.
- Check if n2 or any of its ancestors exist in hash table, if yes return the first existing ancestor.
Below is the implementation of above steps.
LCA of 10 and 8 is 8
Note : The above implementation uses insert of Binary Search Tree to create a Binary Tree, but the function LCA is for any Binary Tree (not necessarily a Binary Search Tree). Time Complexity : O(h) where h is height of Binary Tree if we use hash table to implement the solution (Note that the above solution uses map which takes O(Log h) time to insert and find). So the time complexity of above implementation is O(h Log h). Auxiliary Space : O(h) A O(h) time and O(1) Extra Space Solution: The above solution requires extra space because we need to use a hash table to store visited ancestors. We can solve the problem in O(1) extra space using following fact : 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. The idea is to find depths of given nodes and move up the deeper node pointer by the difference between depths. Once both nodes reach same level, traverse them up and return the first common node. Thanks to Mysterious Mind for suggesting this approach.
LCA of 10 and 22 is 20
Time Complexity : O(h)
Space Complexity : O(1)
You may like to see below articles as well : Lowest Common Ancestor in a Binary Tree | Set 1 Lowest Common Ancestor in a Binary Search Tree. Find LCA in Binary Tree using RMQ This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Please Login to comment...