Print the nodes at odd levels of a tree | Iterative C ++ program to print odd level nodes ; Iterative method to do level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue root and initialize level as odd ; nodeCount ( queue size ) indicates number of nodes at current level . ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Utility method to create a node ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left , * right ; } ; void printOddNodes ( Node * root ) { if ( root == NULL ) return ; queue < Node * > q ; q . push ( root ) ; bool isOdd = true ; while ( 1 ) { int nodeCount = q . size ( ) ; if ( nodeCount == 0 ) break ; while ( nodeCount > 0 ) { Node * node = q . front ( ) ; if ( isOdd ) cout << node -> data << " ▁ " ; q . pop ( ) ; if ( node -> left != NULL ) q . push ( node -> left ) ; if ( node -> right != NULL ) q . push ( node -> right ) ; nodeCount -- ; } isOdd = ! isOdd ; } } struct Node * newNode ( int data ) { struct Node * node = new Node ; node -> data = data ; node -> left = node -> right = NULL ; return ( node ) ; } int main ( ) { struct Node * root = newNode ( 1 ) ; root -> left = newNode ( 2 ) ; root -> right = newNode ( 3 ) ; root -> left -> left = newNode ( 4 ) ; root -> left -> right = newNode ( 5 ) ; printOddNodes ( root ) ; return 0 ; }