Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)

Given a rooted tree, and two nodes which are in the tree, find the Lowest common ancestor of both the nodes. The LCA for two nodes u and v is defined as the farthest node from the root that is the ancestor to both u and v.
Prerequisites : LCA | SET 1

Example for above figure :

Input : 4 5
Output : 2

Input : 4 7
Output : 1

Recommended: Please try your approach on {IDE} first, before moving on to the solution.

Converting LCA to RMQ(Range Minimum Query):
Take an array named E[], which stores the order of dfs traversal i.e. the order in which the nodes are covered during the dfs traversal. For example,

The tree given above has dfs traversal in the order: 1-2-4-2-5-2-1-3.

Take another array L[], in which L[i] is the level of node E[i].

And the array H[], which stores the index of the first occurrence of ith node in the array E[].

So, for the above tree,
E[] = {1, 2, 4, 2, 5, 2, 1, 3}
L[] = {1, 2, 3, 2, 3, 2, 1, 2}
H[] = {0, 1, 7, 2, 4}
Note that the arrays E and L are with one-based indexing but the array H has zero-based indexing.

Now, to find the LCA(4, 3), first, use the array H and find the indices at which 4 and 3 are found in E i.e. H[4] and H[3]. So, the indices come out to be 2 and 7. Now, look at the subarray L[2 : 7], and find the minimum in this subarray which is 1 (at the 6th index), and the corresponding element in the array E i.e. E[6] is the LCA(4, 3).

To understand why this works, take LCA(4, 3) again. The path by which one can reach node 3 from node 4 is the subarray E[2 : 7]. And, if there is a node with the lowest level in this path, then it can simply be claimed to be the LCA(4, 3).

Now, the problem is to find the minimum in the subarray E[H[u]….H[v]] (assuming that H[u] >= H[v]). And, that could be done using a segment tree or sparse table. Below is the code using the segment tree.

Python3

Output:

7
5

Time Complexity :
The arrays defined are stored in O(n). The segment tree construction also takes O(n) time. The LCA function calls the function RMQ which takes O(logn) per query (as it uses the segment tree). So overall time complexity is O(n + q * logn).

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.

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.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.

Improved By : ankush_953, sanjeev2552

Article Tags :
Practice Tags :

3

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.