Kth ancestor of all nodes in an N-ary tree using DFS
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.
Input: K = 2
Output: -1 -1 -1 1 1 1 1 1 1
2nd ancestor does not exist for nodes 1, 2 and 3
2nd ancestor of nodes 4, 5, 6, 7, 8, 9 is 1.
Input: K = 1
Output: -1 1 1 2 2 2 3 3 3
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. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.