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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- LCA in a tree using Binary Lifting Technique
- K-th ancestor of a node in Binary Tree | Set 3
- Kth ancestor of a node in binary tree | Set 2
- K-th ancestor of a node in Binary Tree
- Maximum difference between node and its ancestor in Binary Tree
- Maximum weighted edge in path between two nodes in an N-ary tree using binary lifting
- 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 Tree | Set 1
- Lowest Common Ancestor in a Binary Search Tree.
- Least Common Ancestor of any number of nodes in Binary Tree
- Construct Binary Tree from Ancestor Matrix | Top Down Approach
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Search a node in Binary Tree
- Get Level of a node in a Binary Tree
- Sum of cousins of a given node in a Binary Tree
- Total sum except adjacent of a given node in a Binary Tree
- Closest leaf to a given node in Binary Tree
- Preorder Successor of a Node in Binary Tree
- Kth node in Diagonal Traversal of 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.