Print alternate nodes from all levels of a Binary Tree | C ++ program to implement the above approach ; Structure of a Node ; Print alternate nodes of a binary tree ; Store nodes of each level ; Store count of nodes of current level ; Print alternate nodes of the current level ; If left child exists ; Store left child ; If right child exists ; Store right child ; Driver Code ; Create a tree
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left ; Node * right ; Node ( int val ) { data = val ; left = right = NULL ; } } ; void PrintAlternate ( Node * root ) { queue < Node * > Q ; Q . push ( root ) ; while ( ! Q . empty ( ) ) { int N = Q . size ( ) ; for ( int i = 0 ; i < N ; i ++ ) { Node * temp = Q . front ( ) ; Q . pop ( ) ; if ( i % 2 == 0 ) { cout << temp -> data << " ▁ " ; } if ( temp -> left ) { Q . push ( temp -> left ) ; } if ( temp -> right ) { Q . push ( temp -> right ) ; } } cout << endl ; } } int main ( ) { Node * root ; root = new Node ( 71 ) ; root -> left = new Node ( 88 ) ; root -> right = new Node ( 99 ) ; root -> left -> left = new Node ( 4 ) ; root -> left -> right = new Node ( 5 ) ; root -> right -> left = new Node ( 6 ) ; root -> right -> right = new Node ( 7 ) ; root -> left -> left -> left = new Node ( 8 ) ; root -> left -> left -> right = new Node ( 9 ) ; root -> left -> right -> left = new Node ( 10 ) ; root -> left -> right -> right = new Node ( 11 ) ; root -> right -> left -> right = new Node ( 13 ) ; root -> right -> right -> left = new Node ( 14 ) ; PrintAlternate ( root ) ; }