Run this while loop till queue got empty
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 ) ; }