Perfect Binary Tree Specific Level Order Traversal | Set 2 | Java 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
import java . util . * ; class GFG { static class Node { int data ; Node left ; Node right ; Node ( int value ) { data = value ; left = null ; right = null ; } } ; static void specific_level_order_traversal ( Node root ) { Queue < Node > q = new LinkedList < > ( ) ; Stack < Vector < Integer > > s = new Stack < Vector < Integer > > ( ) ; q . add ( root ) ; int sz ; while ( q . size ( ) > 0 ) { Vector < Integer > v = new Vector < Integer > ( ) ; sz = q . size ( ) ; for ( int i = 0 ; i < sz ; ++ i ) { Node temp = q . peek ( ) ; q . remove ( ) ; v . add ( temp . data ) ; if ( temp . left != null ) q . add ( temp . left ) ; if ( temp . right != null ) q . add ( temp . right ) ; } s . push ( v ) ; } while ( s . size ( ) > 0 ) { Vector < Integer > v = s . peek ( ) ; s . pop ( ) ; for ( int i = 0 , j = v . size ( ) - 1 ; i < j ; ++ i ) { System . out . print ( v . get ( i ) + " ▁ " + v . get ( j ) + " ▁ " ) ; j -- ; } } System . out . println ( root . data ) ; } public static void main ( String args [ ] ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; System . out . println ( " Specific ▁ Level ▁ Order ▁ traversal " + " ▁ of ▁ binary ▁ tree ▁ is " ) ; specific_level_order_traversal ( root ) ; } }