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)
- Print all the levels with odd and even number of nodes in it | Set-2
- Print the nodes at odd levels of a tree
- Print Levels of all nodes in a Binary Tree
- Print all nodes between two given levels in Binary Tree
- Given a n-ary tree, count number of nodes which have more number of children than parents
- Calculate number of nodes in all subtrees | Using DFS
- Number of nodes greater than a given value in n-ary tree
- Number of special nodes in an n-ary tree
- Count the number of non-reachable nodes
- Level with maximum number of nodes
- Number of Unicolored Paths between two nodes
- Level with maximum number of nodes using DFS in a N-ary tree
- Count the number of nodes at given level in a tree using BFS.
- Minimize the number of weakly connected nodes
- Count the number of nodes at a given level in a tree using DFS
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.