Given an integer n. There’s a full binary tree with 2n – 1 nodes. The foundation of that tree is the node with the worth 1, and each node with a worth 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 might be given Okay queries of sort (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 } ]
![]()
Full binary tree for given enter n=5
Output: [ 2, 5, 7, 1, 1, 1, 2, 1 ]
Enter: n = 3, queries = [ {2, 5}, {3, 6}, {4, 1}, {7, 3} ]
![]()
Full binary tree for given enter n=3
Output: [2, 3, 1, 3]
Strategy: The issue will be solved primarily based on the next concept:
As all values on a stage are smaller than values on the subsequent stage. Verify which node is having higher worth in a question, and divide it by 2 to succeed in its mum or dad node. Repeat this step till we get frequent aspect.
Observe the steps to unravel the issue:
- In a question, we’re having 2 nodes a and b, whose lowest frequent ancestor we’ve to search out.
- By dividing the worth of the node by 2, we’ll all the time get the mum or dad node worth.
- From a and b whichever node is having higher worth divide by 2. So, as to maneuver in direction of the basis of the basis.
- When a and b turns into equal, the frequent ancestor between them is bought and returned.
Under is the implementation for the strategy mentioned:
C++
|
|
Time Complexity: O(n)
Auxiliary Area: O(1)
Associated Articles: