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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
- Lowest Common Ancestor in a Binary Tree | Set 1
- Lowest Common Ancestor for a Set of Nodes in a Rooted Tree
- 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
- Least Common Ancestor of any number of nodes in Binary Tree
- 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
- Shortest path between two nodes in array like representation of binary tree
- Minimum sub-array such that number of 1's in concatenation of binary representation of its elements is at least K
- Maximum number of consecutive 1's in binary representation of all the array elements
- Find K items with the lowest values
- Count pairs in an array which have at least one digit common
- Print common nodes on path from root (or common ancestors)
- Remove minimum number of elements such that no common element exist in both array
- Find the occurrence of the given binary pattern in the binary representation of the array elements
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.