Given a N-ary tree, the task is to print the level with the maximum number of nodes.
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
- 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 first level to last level, and find the level with the maximum number of nodes.
- Re-traverse from first to last level, and print all the levels which have the same number of maximum nodes.
Below is the implementation of the above approach.
The levels with maximum number of nodes are: 3 4
Time Complexity: O(N)
Auxiliary Space: O(N)