Level order traversal with direction change after every two levels | Javascript program to print Zig - Zag traversal in groups of size 2. ; A Binary Tree Node ; Utility function to create a new tree node ; Function to print the level order of given binary tree . Direction of printing level order traversal of binary tree changes after every two levels ; Run this while loop till queue got empty ; For printing nodes from right to left , push the nodes to stack instead of printing them . ; for printing the nodes in order from right to left ; Change the direction of traversal . ; Let us create binary tree
let LEFT = 0 ; let RIGHT = 1 ; function ChangeDirection ( Dir ) { Dir = 1 - Dir ; return Dir ; } class Node { constructor ( data ) { this . data = data ; this . left = this . right = null ; } } function modifiedLevelOrder ( root ) { if ( root == null ) return ; let dir = LEFT ; let temp ; let Q = [ ] ; let S = [ ] ; S . push ( root ) ; while ( Q . length != 0 S . length != 0 ) { while ( S . length != 0 ) { temp = S . pop ( ) ; document . write ( temp . data + " " ) ; if ( dir == LEFT ) { if ( temp . left != null ) Q . push ( temp . left ) ; if ( temp . right != null ) Q . push ( temp . right ) ; } else { if ( temp . right != null ) Q . push ( temp . right ) ; if ( temp . left != null ) Q . push ( temp . left ) ; } } document . write ( " " ) ; while ( Q . length != 0 ) { temp = Q [ 0 ] ; Q . shift ( ) ; document . write ( temp . data + " " ) ; if ( dir == LEFT ) { if ( temp . left != null ) S . push ( temp . left ) ; if ( temp . right != null ) S . push ( temp . right ) ; } else { if ( temp . right != null ) S . push ( temp . right ) ; if ( temp . left != null ) S . push ( temp . left ) ; } } document . write ( " " ) ; dir = ChangeDirection ( dir ) ; } } let root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; 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 ( 3 ) ; root . left . right . right = new Node ( 1 ) ; root . right . left . left = new Node ( 4 ) ; root . right . left . right = new Node ( 2 ) ; root . right . right . left = new Node ( 7 ) ; root . right . right . right = new Node ( 2 ) ; root . left . right . left . left = new Node ( 16 ) ; root . left . right . left . right = new Node ( 17 ) ; root . right . left . right . left = new Node ( 18 ) ; root . right . right . left . right = new Node ( 19 ) ; modifiedLevelOrder ( root ) ;