Flip Binary Tree | C # program to flip a binary tree ; A binary tree node ; Utility function to create a new Binary Tree Node ; method to flip the binary tree ; Initialization of pointers ; Iterate through all left nodes ; Swapping nodes now , need temp to keep the previous right child Making prev ' s ▁ right ▁ ▁ as ▁ curr ' s left child ; Storing curr 's right child ; Making prev as curr 's  right child ; 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
using System ; using System . Collections . Generic ; class GFG { public class Node { public int data ; public Node left , right ; } public static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } public static Node flipBinaryTree ( Node root ) { Node curr = root ; Node next = null ; Node temp = null ; Node prev = null ; while ( curr != null ) { next = curr . left ; curr . left = temp ; temp = curr . right ; curr . right = prev ; prev = curr ; curr = next ; } return prev ; } public static void printLevelOrder ( Node root ) { if ( root == null ) { return ; } LinkedList < Node > q = new LinkedList < Node > ( ) ; q . AddLast ( root ) ; while ( true ) { int nodeCount = q . Count ; if ( nodeCount == 0 ) { break ; } while ( nodeCount > 0 ) { Node node = q . First . Value ; Console . Write ( node . data + " ▁ " ) ; q . RemoveFirst ( ) ; if ( node . left != null ) { q . AddLast ( node . left ) ; } if ( node . right != null ) { q . AddLast ( node . right ) ; } nodeCount -- ; } Console . WriteLine ( ) ; } } public static void Main ( string [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . right . left = newNode ( 4 ) ; root . right . right = newNode ( 5 ) ; Console . Write ( " Level ▁ order ▁ traversal ▁ " + " of ▁ given ▁ tree STRNEWLINE " ) ; printLevelOrder ( root ) ; root = flipBinaryTree ( root ) ; Console . Write ( " STRNEWLINE Level ▁ order ▁ traversal ▁ " + " of ▁ the ▁ flipped ▁ tree STRNEWLINE " ) ; printLevelOrder ( root ) ; } }