Print levels with odd number of nodes and even number of nodes
Given an N-ary tree, print all the levels with odd and even number of nodes in it.
For example consider the following tree 1 - Level 1 / \ 2 3 - Level 2 / \ \ 4 5 6 - Level 3 / \ / 7 8 9 - Level 4 The levels with odd number of nodes are: 1 3 4 The levels with even number of nodes are: 2
Note: The level numbers starts from 1. That is, the root node is at the level 1.
- 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 print all nodes with count values as odd to get level with odd number nodes.
- Iterate from first level to last level, and print all nodes with count values as even to get level with even number nodes.
Below is the implementation of the above approach:
The levels with odd number of nodes are: 1 3 4 The levels with even number of nodes are: 2
Time Complexity: O(N)
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.