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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Lowest Common Ancestor in a Binary Search Tree.
- Lowest Common Ancestor in a Binary Tree | Set 1
- Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
- Lowest Common Ancestor for a Set of Nodes in a Rooted Tree
- Tarjan's off-line lowest common ancestors algorithm
- Construct Binary Tree from given Parent Array representation
- Construct Binary Tree from given Parent Array representation | Iterative Approach
- Least Common Ancestor of any number of nodes in Binary Tree
- Find K items with the lowest values
- Print common nodes on path from root (or common ancestors)
- Maximum difference between node and its ancestor in Binary Tree
- Kth ancestor of a node in binary tree | Set 2
- Level Ancestor Problem
- Minimum number of groups of nodes such that no ancestor is present in the same group
- K-th ancestor of a node in Binary Tree | Set 3
- Kth ancestor of a node in an N-ary tree using Binary Lifting Technique
- Kth ancestor of all nodes in an N-ary tree using DFS
- Construct Binary Tree from Ancestor Matrix | Top Down Approach
- Construct tree from ancestor matrix
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.