Print siblings of a given Node in N-ary Tree
Given an N-ary tree and an element X, the task is to print the siblings of the node with value X.
Two nodes are considered to be siblings if they are present at the same level and have the same parent.
Input: X = 100
Output: 90 110
Explanation: Nodes valued 90, 100 and 110 have the same parent, i.e. the node valued 40. Therefore, nodes 90 and 110 are the siblings of the given node X( = 100).
Input: X = 30
Output: 20 40
Explanation: Nodes valued 20, 30 and 40 have the same parent, i.e. the node valued 10. Therefore, nodes 20 and 40 are the siblings of the given node X( = 30).
Approach: Follow the steps given below to solve the problem:
- Perform level order traversal on the given N-ary tree.
- Initialize a queue q for level order traversal.
- For every node encountered, push all its children into the queue.
- While pushing the children of the current node into the queue, check: if any of these children is equal to the given value X or not. If found to be true, then print all nodes except X which are children of the current as the required answer.
- Otherwise, continue to traversing the tree.
Below is the implementation of the above approach:
Time Complexity: O(N2)
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.