Sunday, February 5, 2023
HomeSoftware DevelopmentDiscover LCA for Okay queries in Full Binary Tree

Discover LCA for Okay queries in Full Binary Tree


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 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 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 might be solved based mostly on the next concept:

As all values on a stage are smaller than values on the following stage. Verify which node is having better worth in a question, and divide it by 2 to succeed in its father or mother node. Repeat this step till we get frequent factor. 

Comply with the steps to unravel the issue:

  • In a question, we’re having 2 nodes a and b, whose lowest frequent ancestor we now have to seek out.
  • By dividing the worth of the node by 2, we are going to all the time get the father or mother 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++

#embrace <bits/stdc++.h>

utilizing namespace std;

  

int helper(int a, int b)

{

  

    whereas (a != b) {

  

        if (a > b)

            a = a / 2;

  

        else

            b = b / 2;

    }

  

    return a;

}

  

int principal()

{

  

    

    

    int n = 5;

  

    

    vector<vector<int> > queries

        = { { 17, 21 }, { 23, 5 }, { 15, 7 }, { 3, 21 }, { 31, 9 }, { 5, 15 }, { 11, 2 }, { 19, 7 } };

  

    

    

    for (auto e : queries) {

  

        

        int lca = helper(e[0], e[1]);

  

        cout << lca << ' ';

    }

  

    return 0;

}

Time Complexity: O(n)
Auxiliary House: O(1)

Associated Articles:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments