Print all the levels with odd and even number of nodes in it | Set-2

Given an N-ary tree, print all the levels with odd and even number of nodes in it.

Examples:

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.

Approach:

  • Insert all the connecting nodes to a 2-D vector tree.
  • Run a BFS on the tree such that height[node] = 1 + height[parent]
  • Once BFS 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

chevron_right


Output:

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)



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.