Given a node x, find the number of children of x(if it exists) in the given n-ary tree.
👁 Image
Example :
Input : x = 50
Output : 3
Explanation : 50 has 3 children having values 40, 100 and 20.
Approach :
- Initialize the number of children as 0.
- For every node in the n-ary tree, check if its value is equal to x or not. If yes, then return the number of children.
- If the value of x is not equal to the current node then, push all the children of current node in the queue.
- Keep Repeating the above step until the queue becomes empty.
Below is the implementation of the above idea :
Complexity Analysis:
- Time Complexity : O(N), where N is the number of nodes in tree.
- Auxiliary Space : O(N), where N is the number of nodes in tree.