Level order traversal with direction change after every two levels | A Binary 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 ; For null root ; Maintain a queue for normal level order traversal ; Maintain a stack for printing nodes in reverse order after they are popped out from queue . ; sz is used for storing the count of nodes in a level ; Used for changing the direction of level order traversal ; Used for changing the direction of level order traversal ; Push root node to the queue ; Run this while loop till queue got empty ; Do a normal level order traversal ; For printing nodes from left to right , simply print the nodes in the order in which they are being popped out from the queue . ; 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 printing nodes after every two levels . ; Let us create binary tree
class Node { constructor ( data ) { this . data = data ; this . left = this . right = null ; } } function modifiedLevelOrder ( node ) { if ( node == null ) return ; if ( node . left == null && node . right == null ) { document . write ( node . data ) ; return ; } let myQueue = [ ] ; let myStack = [ ] ; let temp = null ; let sz ; let ct = 0 ; let rightToLeft = false ; myQueue . push ( node ) ; while ( myQueue . length != 0 ) { ct ++ ; sz = myQueue . length ; for ( let i = 0 ; i < sz ; i ++ ) { temp = myQueue . shift ( ) ; if ( rightToLeft == false ) document . write ( temp . data + " " ) ; else myStack . push ( temp ) ; if ( temp . left != null ) myQueue . push ( temp . left ) ; if ( temp . right != null ) myQueue . push ( temp . right ) ; } if ( rightToLeft == true ) { while ( myStack . length != 0 ) { temp = myStack . pop ( ) ; document . write ( temp . data + " " ) ; } } if ( ct == 2 ) { rightToLeft = ! rightToLeft ; ct = 0 ; } document . write ( " " ) ; } } 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 ) ;