Given a binary tree represented as parent array, find Lowest Common Ancestor between two nodes ‘m’ and ‘n’.
In the above diagram, LCA of 10 and 14 is 12 and LCA of 10 and 12 is 12.
(1) Make a parent array and store the parent of ith node in it. Parent of root node should be -1.
(2) Now, access all the nodes from the desired node ‘m’ till root node and mark them visited.
(3) Lastly, access all the nodes from the desired node ‘n’ till first visited node comes.
(4) This node is the lowest common ancestor
Time Complexity – The time complexity of the above algorithm is O(log n) as it requires O(log n) time in searching.
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Lowest Common Ancestor in a Binary Tree | Set 1
- Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
- Lowest Common Ancestor in a Binary Search Tree.
- Construct Binary Tree from given Parent Array representation
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Tarjan's off-line lowest common ancestors algorithm
- Height of n-ary tree if parent array is given
- Height of a generic tree from parent array
- Find Height of Binary Tree represented by Parent array
- Minimum sub-array such that number of 1's in concatenation of binary representation of its elements is at least K
- Shortest path between two nodes in array like representation of binary tree
- Count pairs in an array which have at least one digit common
- Find K items with the lowest values
- Print common nodes on path from root (or common ancestors)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.