Find the cousins of a given element in an N-ary tree
Given an N-array tree root and an integer K, the task is to print all the cousins of node K.
Note: Two nodes are considered to be cousins if they have the same depth (are on the same level) and have different parents.
Consider the below tree:
Input: K = 39
Output: 88 98 61 74 17 72 19
Input: K = 17
Output: 88 98 61 74 39
Input: K = 90
Approach: The idea is to do a level order traversal. During the traversal, if we find a node whose child is equal to the given element, then we will not push the children of this node. We will push the children of the other nodes and the inner loop will end when all the elements of that level are traversed. Follow the steps below to solve the problem:
- If root equals null, then return.
- Initialize the queue q and push root into the queue q.
- Initialize the boolean variable found as false.
- Initialize the variables qsize as 0 and node temp.
- Iterate over the while loop till q is not empty and node is not found and perform the following tasks:
- Set size qsize as the size of the queue q.
- Iterate over the while loop till qsize is greater than 0 and perform the following tasks:
- Set tempp as the front of the queue q.
- De queue from the queue q.
- If found equals true, then push all it’s children into the queue q.
- Iterate over the range [0, temp->child.size()) using the variable i and perform the following tasks:
- If the child is not null and it’s key equals value, then set the value of found as true.
- If found is false, then push all it’s children into the queue q.
- Decrease the value of qsize by 1.
- If found is false, then print “Not Possible.”
- Else, Initialize the variables qsize as the size of the queue q.
- If qsize equals 0 then print “No Cousins”.
- Else, print all the elements of the queue q.
Below is the implementation of the above approach
Cousins for the element 39: 88 98 61 74 17 72 19
Time Complexity: O(N)
Auxiliary Space: O(N)