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 kids the place the left node has the worth
2*x and the proper node has the worth 2*x + 1, you’re given Ok queries of kind (ai, bi), and the duty is to return the LCA for the node pair ai and bi for all Ok 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]
Method: The issue may be solved based mostly on the next concept:
As all values on a degree are smaller than values on the subsequent degree. Verify which node is having better worth in a question, and divide it by 2 to achieve its dad or mum node. Repeat this step till we get frequent ingredient.
Comply with 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 at all times get the dad or mum node worth.
- From a and b whichever node is having better worth divide by 2. So, as to maneuver in direction of the foundation of the foundation.
- When a and b turns into equal, the frequent ancestor between them is obtained and returned.
Beneath is the implementation for the strategy mentioned:
C++
// C++ code for the above strategy #embrace <bits/stdc++.h> utilizing namespace std; // Operate to search out lca for // given two nodes in tree int helper(int a, int b) { whereas (a != b) { if (a > b) a = a / 2; else b = b / 2; } return a; } // Driver code int foremost() { // 2^n - 1 nodes in full // binary tree int n = 5; // Queries enter vector vector<vector<int> > queries = { { 17, 21 }, { 23, 5 }, { 15, 7 }, { 3, 21 }, { 31, 9 }, { 5, 15 }, { 11, 2 }, { 19, 7 } }; // Processing every question in // queries vector for (auto e : queries) { // Operate name int lca = helper(e[0], e[1]); cout << lca << ' '; } return 0; }
Time Complexity: O(n)
Auxiliary Area: O(1)
Associated Articles: