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.
Input: K = 2, V = 4
2nd parent of vertex 4 is 1.
Input: K = 3, V = 4
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:
Time Complexity: O(NlogN) for pre-processing and logN for finding the ancestor.
- LCA in a tree using Binary Lifting Technique
- K-th ancestor of a node in Binary Tree | Set 3
- K-th ancestor of a node in Binary Tree
- Kth ancestor of a node in binary tree | Set 2
- Maximum difference between node and its ancestor in Binary Tree
- Lowest Common Ancestor in a Binary Tree | Set 1
- Construct Ancestor Matrix from a Given Binary Tree
- Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
- Lowest Common Ancestor in a Binary Search Tree.
- Construct Binary Tree from Ancestor Matrix | Top Down Approach
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Sum of cousins of a given node in a Binary Tree
- Search a node in Binary Tree
- Get Level of a node in a Binary Tree
- Print cousins of a given node in Binary Tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.