Flip Binary Tree | A binary tree node structure ; method to flip the binary tree ; recursively call the same method ; rearranging main root Node after returning from recursive call ; Iterative method to do level order traversal line by line ; Base Case ; Create an empty queue for level order traversal ; Enqueue Root and initialize height ; nodeCount ( queue size ) indicates number of nodes at current lelvel . ; Dequeue all nodes of current level and Enqueue all nodes of next level ; Driver code
class Node { constructor ( data ) { this . data = data ; this . left = this . right = null ; } } ; function flipBinaryTree ( root ) { if ( root == null ) return root ; if ( root . left == null && root . right == null ) return root ; let flippedRoot = flipBinaryTree ( root . left ) ; root . left . left = root . right ; root . left . right = root ; root . left = root . right = null ; return flippedRoot ; } function printLevelOrder ( root ) { if ( root == null ) return ; let q = [ ] ; q . push ( root ) ; while ( true ) { let nodeCount = q . length ; if ( nodeCount == 0 ) break ; while ( nodeCount > 0 ) { let node = q . shift ( ) ; document . write ( node . data + " " ) ; if ( node . left != null ) q . push ( node . left ) ; if ( node . right != null ) q . push ( node . right ) ; nodeCount -- ; } document . write ( " " ) ; } } let root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . right = new Node ( 3 ) ; root . right . left = new Node ( 4 ) ; root . right . right = new Node ( 5 ) ; document . write ( " " ) ; printLevelOrder ( root ) ; root = flipBinaryTree ( root ) ; document . write ( " " ) ; printLevelOrder ( root ) ;