Given an N-ary tree and an integer K, the task is to print the Kth ancestors of all the nodes of the tree in level order manner. If K ancestors does not exist for a node, then print -1 for that node.
Approach: The approach is to use DFS to find the ancestors of all the nodes. Below are the steps:
- The Kth parent of any node can be found by using DFS, and storing all parents of a node in a temporary vector say temp.
- Whenever a node is visited in DFS, it is pushed in the temp vector.
- At the end of DFS, the currently visited node is popped from the temp vector.
- For the currently visited node, the vector contains all the ancestors of the node.
- The Kth node from the end of the vector is the Kth ancestor of the currently visited node, so store it in a ancestor array.
Below is the implementation of the above approach:
-1 -1 -1 1 1 1 1 1 1
Time complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Kth ancestor of a node in an N-ary tree using Binary Lifting Technique
- Kth ancestor of a node in binary tree | Set 2
- Subtree of all nodes in a tree using DFS
- Print all leaf nodes of an n-ary tree using DFS
- Find the Kth node in the DFS traversal of a given subtree in a Tree
- Level with maximum number of nodes using DFS in a N-ary tree
- Count the number of nodes at a given level in a tree using DFS
- Least Common Ancestor of any number of nodes in Binary Tree
- Lowest Common Ancestor for a Set of Nodes in a Rooted Tree
- Calculate number of nodes in all subtrees | Using DFS
- Sum of all nodes at Kth level in a Binary Tree
- Minimum number of groups of nodes such that no ancestor is present in the same group
- Lowest Common Ancestor in a Binary Tree | Set 2 (Using Parent Pointer)
- Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
- Calculate number of nodes between two vertices in an acyclic Graph by DFS method
- Diameter of a tree using DFS
- DFS traversal of a tree using recursion
- Construct the Rooted tree by using start and finish time of its DFS traversal
- Lowest Common Ancestor in a Binary Search Tree.
- Lowest Common Ancestor in a Binary Tree | Set 1
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.