Monday, November 18, 2024
Google search engine
HomeData Modelling & AIKth ancestor of a node in an N-ary tree using Binary Lifting...

Kth ancestor of a node in an N-ary tree using Binary Lifting Technique

Given a vertex V of an N-ary tree and an integer K, the task is to print the Kth ancestor of the given vertex in the tree. If there does not exist any such ancestor then print -1.
Examples: 
 

Input: K = 2, V = 4 
 

Output:
2nd parent of vertex 4 is 1.
Input: K = 3, V = 4 
 

Output: -1 
 

 

Approach: The idea is to use Binary Lifting Technique. This technique is based on the fact that every integer can be represented in binary form. Through pre-processing, a sparse table table[v][i] can be calculated which stores the 2ith parent of the vertex v where 0 ? i ? log2N. This pre-processing takes O(NlogN) time. 
To find the Kth parent of the vertex V, let K = b0b1b2…bn be an n bit number in the binary representation, let p1, p2, p3, …, pj be the indices where bit value is 1 then K can be represented as K = 2p1 + 2p2 + 2p3 + … + 2pj. Thus to reach Kth parent of V, we have to make jumps to 2pth1, 2pth2, 2pth3 upto 2pthj parent in any order. This can be done efficiently through the sparse table calculated earlier in O(logN).
Below is the implementation of the above approach: 
 

C++




// CPP implementation of the approach
#include <bits/stdc++.h>
using namespace std;
 
// Table for storing 2^ith parent
int **table;
 
// To store the height of the tree
int height;
 
// initializing the table and
// the height of the tree
void initialize(int n)
{
    height = (int)ceil(log2(n));
    table = new int *[n + 1];
}
 
// Filling with -1 as initial
void preprocessing(int n)
{
    for (int i = 0; i < n + 1; i++)
    {
        table[i] = new int[height + 1];
        memset(table[i], -1, sizeof table[i]);
    }
}
 
// Calculating sparse table[][] dynamically
void calculateSparse(int u, int v)
{
    // Using the recurrence relation to
    // calculate the values of table[][]
    table[v][0] = u;
    for (int i = 1; i <= height; i++)
    {
        table[v][i] = table[table[v][i - 1]][i - 1];
 
        // If we go out of bounds of the tree
        if (table[v][i] == -1)
            break;
    }
}
 
// Function to return the Kth ancestor of V
int kthancestor(int V, int k)
{
    // Doing bitwise operation to
    // check the set bit
    for (int i = 0; i <= height; i++)
    {
        if (k & (1 << i))
        {
            V = table[V][i];
            if (V == -1)
                break;
        }
    }
    return V;
}
 
// Driver Code
int main()
{
    // Number of vertices
    int n = 6;
 
    // initializing
    initialize(n);
 
    // Pre-processing
    preprocessing(n);
 
    // Calculating ancestors of v
    calculateSparse(1, 2);
    calculateSparse(1, 3);
    calculateSparse(2, 4);
    calculateSparse(2, 5);
    calculateSparse(3, 6);
 
    int K = 2, V = 5;
    cout << kthancestor(V, K) << endl;
 
    return 0;
}
 
// This code is contributed by
// sanjeev2552


Java




// Java implementation of the approach
import java.util.Arrays;
 
class GfG {
 
    // Table for storing 2^ith parent
    private static int table[][];
 
    // To store the height of the tree
    private static int height;
 
    // Private constructor for initializing
    // the table and the height of the tree
    private GfG(int n)
    {
 
        // log(n) with base 2
        height = (int)Math.ceil(Math.log10(n) / Math.log10(2));
        table = new int[n + 1][height + 1];
    }
 
    // Filling with -1 as initial
    private static void preprocessing()
    {
        for (int i = 0; i < table.length; i++) {
            Arrays.fill(table[i], -1);
        }
    }
 
    // Calculating sparse table[][] dynamically
    private static void calculateSparse(int u, int v)
    {
 
        // Using the recurrence relation to
        // calculate the values of table[][]
        table[v][0] = u;
        for (int i = 1; i <= height; i++) {
            table[v][i] = table[table[v][i - 1]][i - 1];
 
            // If we go out of bounds of the tree
            if (table[v][i] == -1)
                break;
        }
    }
 
    // Function to return the Kth ancestor of V
    private static int kthancestor(int V, int k)
    {
 
        // Doing bitwise operation to
        // check the set bit
        for (int i = 0; i <= height; i++) {
            if ((k & (1 << i)) != 0) {
                V = table[V][i];
                if (V == -1)
                    break;
            }
        }
        return V;
    }
 
    // Driver code
    public static void main(String args[])
    {
        // Number of vertices
        int n = 6;
 
        // Calling the constructor
        GfG obj = new GfG(n);
 
        // Pre-processing
        preprocessing();
 
        // Calculating ancestors of v
        calculateSparse(1, 2);
        calculateSparse(1, 3);
        calculateSparse(2, 4);
        calculateSparse(2, 5);
        calculateSparse(3, 6);
 
        int K = 2, V = 5;
        System.out.print(kthancestor(V, K));
    }
}


Python3




# Python3 implementation of the approach
import math
 
class GfG :
 
    # Private constructor for initializing
    # the table and the height of the tree
    def __init__(self, n):
     
        # log(n) with base 2
        # To store the height of the tree
        self.height = int(math.ceil(math.log10(n) / math.log10(2)))
         
        # Table for storing 2^ith parent
        self.table = [0] * (n + 1)
     
    # Filling with -1 as initial
    def preprocessing(self):
        i = 0
        while ( i < len(self.table)) :
            self.table[i] = [-1]*(self.height + 1)
            i = i + 1
         
    # Calculating sparse table[][] dynamically
    def calculateSparse(self, u, v):
     
        # Using the recurrence relation to
        # calculate the values of table[][]
        self.table[v][0] = u
        i = 1
        while ( i <= self.height) :
            self.table[v][i] = self.table[self.table[v][i - 1]][i - 1]
 
            # If we go out of bounds of the tree
            if (self.table[v][i] == -1):
                break
            i = i + 1
         
    # Function to return the Kth ancestor of V
    def kthancestor(self, V, k):
        i = 0
 
        # Doing bitwise operation to
        # check the set bit
        while ( i <= self.height) :
            if ((k & (1 << i)) != 0) :
                V = self.table[V][i]
                if (V == -1):
                    break
            i = i + 1
         
        return V
     
# Driver code
 
# Number of vertices
n = 6
 
# Calling the constructor
obj = GfG(n)
 
# Pre-processing
obj.preprocessing()
 
# Calculating ancestors of v
obj.calculateSparse(1, 2)
obj.calculateSparse(1, 3)
obj.calculateSparse(2, 4)
obj.calculateSparse(2, 5)
obj.calculateSparse(3, 6)
 
K = 2
V = 5
print(obj.kthancestor(V, K))
     
# This code is contributed by Arnab Kundu


C#




// C# implementation of the approach
using System;
 
class GFG
{
     
    class GfG
    {
     
        // Table for storing 2^ith parent
        private static int [,]table ;
     
        // To store the height of the tree
        private static int height;
     
        // Private constructor for initializing
        // the table and the height of the tree
        private GfG(int n)
        {
     
            // log(n) with base 2
            height = (int)Math.Ceiling(Math.Log10(n) / Math.Log10(2));
            table = new int[n + 1, height + 1];
        }
     
        // Filling with -1 as initial
        private static void preprocessing()
        {
            for (int i = 0; i < table.GetLength(0); i++)
            {
                for (int j = 0; j < table.GetLength(1); j++)
                {
                    table[i, j] = -1;
                }
            }
        }
     
        // Calculating sparse table[,] dynamically
        private static void calculateSparse(int u, int v)
        {
     
            // Using the recurrence relation to
            // calculate the values of table[,]
            table[v, 0] = u;
            for (int i = 1; i <= height; i++)
            {
                table[v, i] = table[table[v, i - 1], i - 1];
     
                // If we go out of bounds of the tree
                if (table[v, i] == -1)
                    break;
            }
        }
     
        // Function to return the Kth ancestor of V
        private static int kthancestor(int V, int k)
        {
     
            // Doing bitwise operation to
            // check the set bit
            for (int i = 0; i <= height; i++)
            {
                if ((k & (1 << i)) != 0)
                {
                    V = table[V, i];
                    if (V == -1)
                        break;
                }
            }
            return V;
        }
     
        // Driver code
        public static void Main()
        {
            // Number of vertices
            int n = 6;
     
            // Calling the constructor
            GfG obj = new GfG(n);
     
            // Pre-processing
            preprocessing();
     
            // Calculating ancestors of v
            calculateSparse(1, 2);
            calculateSparse(1, 3);
            calculateSparse(2, 4);
            calculateSparse(2, 5);
            calculateSparse(3, 6);
     
            int K = 2, V = 5;
            Console.Write(kthancestor(V, K));
        }
    }
}
 
// This code is contributed by AnkitRai01


Javascript




<script>
    // Javascript implementation of the approach
     
    // Table for storing 2^ith parent
    let table;
   
    // To store the height of the tree
    let height;
       
    // initializing the table and
    // the height of the tree
    function initialize(n)
    {
        height = Math.ceil(Math.log2(n));
    }
   
    // Filling with -1 as initial
    function preprocessing()
    {
        table = new Array(n + 1);
        for (let i = 0; i < n + 1; i++) {
            table[i] = new Array(height + 1);
            for (let j = 0; j < height + 1; j++) {
                table[i][j] = -1;
            }
        }
    }
   
    // Calculating sparse table[][] dynamically
    function calculateSparse(u, v)
    {
   
        // Using the recurrence relation to
        // calculate the values of table[][]
        table[v][0] = u;
        for (let i = 1; i <= height; i++) {
            table[v][i] = table[table[v][i - 1]][i - 1];
   
            // If we go out of bounds of the tree
            if (table[v][i] == -1)
                break;
        }
    }
   
    // Function to return the Kth ancestor of V
    function kthancestor(V, k)
    {
   
        // Doing bitwise operation to
        // check the set bit
        for (let i = 0; i <= height; i++) {
            if ((k & (1 << i)) != 0) {
                V = table[V][i];
                if (V == -1)
                    break;
            }
        }
        return V;
    }
     
    // Number of vertices
    let n = 6;
 
    // Calling the constructor
    initialize(n);
 
    // Pre-processing
    preprocessing();
 
    // Calculating ancestors of v
    calculateSparse(1, 2);
    calculateSparse(1, 3);
    calculateSparse(2, 4);
    calculateSparse(2, 5);
    calculateSparse(3, 6);
 
    let K = 2, V = 5;
    document.write(kthancestor(V, K));
 
// This code is contributed by divyeshrabadiya07.
</script>


Output: 

1

 

Time Complexity: O(NlogN) for pre-processing and logN for finding the ancestor.

Auxiliary Space:  O(NlogN), since we need to store the sparse table with n rows and logn columns, and each cell stores an integer value.
 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments