Given a N-ary tree, the task is to print the level with the maximum number of nodes.
Examples:
Input : For example, consider the following tree
1 - Level 1
/ \
2 3 - Level 2
/ \ \
4 5 6 - Level 3
/ \ /
7 8 9 - Level 4
Output : Level-3 and Level-4
Approach:
- Insert all the connecting nodes to a 2-D vector tree.
- Run a DFS on the tree such that height[node] = 1 + height[parent]
- Once DFS traversal is completed, increase the count[] array by 1, for every node’s level.
- Iterate from the first level to the last level, and find the level with the maximum number of nodes.
- Re-traverse from the first to the last level, and print all the levels which have the same number of maximum nodes.
Below is the implementation of the above approach.
OutputThe levels with maximum number of nodes are: 3 4
Complexity Analysis:
- Time Complexity: O(N), as we are using recursion for traversing all the nodes, though we are using a for loop to traverse all the N nodes, but we are calling the function only if the node is node visited therefore the effective time complexity will be O(N).
- Auxiliary Space: O(N), as we are using extra space for an array to keep track of the visited nodes.