Given an integer n. There’s a full binary tree with 2n – 1 nodes. The basis of that tree is the node with the worth 1, and each node with a price x has two youngsters the place the left node has the worth
2*x and the proper node has the worth 2*x + 1, you’re given Okay queries of kind (ai, bi), and the duty is to return the LCA for the node pair ai and bi for all Okay queries.
Examples:
Enter: n = 5, queries = [ { 17, 21 }, { 23, 5 }, { 15, 7 }, { 3, 21 }, { 31, 9 }, { 5, 15 }, { 11, 2 }, { 19, 7 } ]
Output: [ 2, 5, 7, 1, 1, 1, 2, 1 ]
Enter: n = 3, queries = [ {2, 5}, {3, 6}, {4, 1}, {7, 3} ]
Output: [2, 3, 1, 3]
Method: The issue will be solved primarily based on the next thought:
As all values on a stage are smaller than values on the subsequent stage. Examine which node is having larger worth in a question, and divide it by 2 to succeed in its dad or mum node. Repeat this step till we get widespread component.
Observe the steps to unravel the issue:
- In a question, we’re having 2 nodes a and b, whose lowest widespread ancestor we have now to search out.
- By dividing the worth of the node by 2, we are going to at all times get the dad or mum node worth.
- From a and b whichever node is having larger worth divide by 2. So, as to maneuver in direction of the foundation of the foundation.
- When a and b turns into equal, the widespread ancestor between them is received and returned.
Under is the implementation for the method mentioned:
C++
|
Time Complexity: O(n)
Auxiliary House: O(1)
Associated Articles: