Level order traversal line by line | Set 3 ( Using One Queue ) | A Binary Tree Node ; Prints level order traversal line by line using two queues . ; Create an empty queue for level order traversal ; Pushing root node into the queue . ; Pushing delimiter into the queue . ; Executing loop till queue becomes empty ; condition to check the occurence of next level ; Pushing left child current node ; Pushing right child current node ; Let us create binary tree shown above
class Node { constructor ( data ) { this . data = data ; this . left = null ; this . right = null ; } } function levelOrder ( root ) { if ( root == null ) return ; let q = [ ] ; q . push ( root ) ; q . push ( null ) ; while ( q . length != 0 ) { let curr = q . shift ( ) ; if ( curr == null ) { if ( q . length != 0 ) { q . push ( null ) ; document . write ( " " ) ; } } else { if ( curr . left != null ) q . push ( curr . left ) ; if ( curr . right != null ) q . push ( curr . right ) ; document . write ( curr . data + " " ) ; } } } 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 . right = new Node ( 6 ) ; levelOrder ( root ) ;