Perfect Binary Tree Specific Level Order Traversal | Set 2 | C ++ program for special order traversal ; A binary tree node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new node with the given data and NULL left and right pointers . ; Given a perfect binary tree , print its nodes in specific level order ; for level order traversal ; stack to print reverse ; vector to store the level ; considering size of the level ; push data of the node of a particular level to vector ; push vector containing a level in stack ; print the stack ; Finally pop all Nodes from stack and prints them . ; finally print root ; ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int data ; Node * left ; Node * right ; Node ( int value ) { data = value ; left = NULL ; right = NULL ; } } ; void specific_level_order_traversal ( Node * root ) { queue < Node * > q ; stack < vector < int > > s ; q . push ( root ) ; int sz ; while ( ! q . empty ( ) ) { vector < int > v ; sz = q . size ( ) ; for ( int i = 0 ; i < sz ; ++ i ) { Node * temp = q . front ( ) ; q . pop ( ) ; v . push_back ( temp -> data ) ; if ( temp -> left != NULL ) q . push ( temp -> left ) ; if ( temp -> right != NULL ) q . push ( temp -> right ) ; } s . push ( v ) ; } while ( ! s . empty ( ) ) { vector < int > v = s . top ( ) ; s . pop ( ) ; for ( int i = 0 , j = v . size ( ) - 1 ; i < j ; ++ i ) { cout << v [ i ] << " ▁ " << v [ j ] << " ▁ " ; j -- ; } } cout << root -> data ; } int main ( ) { Node * root = new Node ( 1 ) ; root -> left = new Node ( 2 ) ; root -> right = new Node ( 3 ) ; cout << " Specific ▁ Level ▁ Order ▁ traversal ▁ of ▁ binary ▁ " " tree ▁ is ▁ STRNEWLINE " ; specific_level_order_traversal ( root ) ; return 0 ; }