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 ; Function body ; Create a queue and enqueue left and right children of root ; We process two nodes at a time , so we need two variables to store two front items of queue ; traversal loop ; Pop two items from queue ; Push first and second node 's chilren  in reverse order ; If first and second have grandchildren , enqueue them in specific order ; Given a perfect binary tree , print its nodes in specific level order ; create a stack and push root ; Push level 1 and level 2 nodes in stack ; Since it is perfect Binary Tree , right is not checked ; Do anything more if there are nodes at next level in given perfect Binary Tree ; Finally pop all Nodes from stack and prints them . ; Driver program to test the above functions
import java . util . * ; class Node { int data ; Node left , right ; public Node ( int data ) { this . data = data ; left = right = null ; } } class BinaryTree { Node root ; void printSpecificLevelOrderUtil ( Node root , Stack < Node > s ) { if ( root == null ) return ; Queue < Node > q = new LinkedList < Node > ( ) ; q . add ( root . left ) ; q . add ( root . right ) ; Node first = null , second = null ; while ( ! q . isEmpty ( ) ) { first = q . peek ( ) ; q . poll ( ) ; second = q . peek ( ) ; q . poll ( ) ; s . push ( second . left ) ; s . push ( first . right ) ; s . push ( second . right ) ; s . push ( first . left ) ; if ( first . left . left != null ) { q . add ( first . right ) ; q . add ( second . left ) ; q . add ( first . left ) ; q . add ( second . right ) ; } } } void printSpecificLevelOrder ( Node root ) { Stack < Node > s = new Stack < Node > ( ) ; s . push ( root ) ; if ( root . left != null ) { s . push ( root . right ) ; s . push ( root . left ) ; } if ( root . left . left != null ) printSpecificLevelOrderUtil ( root , s ) ; while ( ! s . empty ( ) ) { System . out . print ( s . peek ( ) . data + " ▁ " ) ; s . pop ( ) ; } } public static void main ( String [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; System . out . println ( " Specific ▁ Level ▁ Order ▁ Traversal ▁ " + " of ▁ Binary ▁ Tree ▁ is ▁ " ) ; tree . printSpecificLevelOrder ( tree . root ) ; }