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.