Given a binary tree, the task is to flip the binary tree towards the right direction that is clockwise.
Input:
Output:
Explanation: In the flip operation, the leftmost node becomes the root of the flipped tree and its parent becomes its right child and the right sibling becomes its left child and the same should be done for all leftmost nodes recursively.
[Expected Approach - 1] Using Recursion - O(n) Time and O(n) Space
The idea is to recursively flip the binary tree by swapping the left and right subtrees of each node. After flipping, the tree's structure will be reversed, and the new root of the flipped tree will be the original leftmost leaf node.
Below is the main rotation code of a subtree:
root->left->left = root->right
root->left->right = root
root->left = NULL
root->right = NULL
Below is the implementation of the above approach:
C++
// C++ program to flip a binary tree // using recursion#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// method to flip the binary tree iterativelyNode*flipBinaryTree(Node*root){// Base casesif(root==nullptr)returnroot;if(root->left==nullptr&&root->right==nullptr)returnroot;// Recursively call the same methodNode*flippedRoot=flipBinaryTree(root->left);// Rearranging main root Node after returning// from recursive callroot->left->left=root->right;root->left->right=root;root->left=root->right=nullptr;returnflippedRoot;}// Iterative method to do level order traversal// line by linevoidprintLevelOrder(Node*root){// Base Caseif(root==nullptr)return;// Create an empty queue for // level order traversalqueue<Node*>q;// Enqueue Root and initialize heightq.push(root);while(1){// nodeCount (queue size) indicates number// of nodes at current level.intnodeCount=q.size();if(nodeCount==0)break;// Dequeue all nodes of current level and// Enqueue all nodes of next levelwhile(nodeCount>0){Node*node=q.front();cout<<node->data<<" ";q.pop();if(node->left!=nullptr)q.push(node->left);if(node->right!=nullptr)q.push(node->right);nodeCount--;}cout<<endl;}}intmain(){// Make a binary tree//// 1// / \ // 2 3// / \ // 4 5 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->right->left=newNode(4);root->right->right=newNode(5);root=flipBinaryTree(root);printLevelOrder(root);return0;}
Java
// Java program to flip a binary tree// using recursionclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Method to flip the binary treestaticNodeflipBinaryTree(Noderoot){// Base casesif(root==null)returnroot;if(root.left==null&&root.right==null)returnroot;// Recursively call the same methodNodeflippedRoot=flipBinaryTree(root.left);// Rearranging main root Node after returning// from recursive callroot.left.left=root.right;root.left.right=root;root.left=root.right=null;returnflippedRoot;}// Iterative method to do level order // traversal line by linestaticvoidprintLevelOrder(Noderoot){// Base Caseif(root==null)return;// Create an empty queue for level // order traversaljava.util.Queue<Node>q=newjava.util.LinkedList<>();// Enqueue Root and initialize heightq.add(root);while(!q.isEmpty()){// nodeCount (queue size) indicates // number of nodes at current levelintnodeCount=q.size();// Dequeue all nodes of current level // and Enqueue all nodes of next levelwhile(nodeCount>0){Nodenode=q.poll();System.out.print(node.data+" ");if(node.left!=null)q.add(node.left);if(node.right!=null)q.add(node.right);nodeCount--;}System.out.println();}}publicstaticvoidmain(String[]args){// Make a binary tree//// 1// / \// 2 3// / \// 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);root=flipBinaryTree(root);printLevelOrder(root);}}
Python
# Python program to flip a binary# tree using recursionclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=NonedefflipBinaryTree(root):# Base casesifrootisNone:returnrootifroot.leftisNoneandroot.rightisNone:returnroot# Recursively call the same methodflippedRoot=flipBinaryTree(root.left)# Rearranging main root Node after returning# from recursive callroot.left.left=root.rightroot.left.right=rootroot.left=root.right=NonereturnflippedRoot# Iterative method to do level order # traversal line by linedefprintLevelOrder(root):# Base CaseifrootisNone:return# Create an empty queue for # level order traversalqueue=[]queue.append(root)whilequeue:nodeCount=len(queue)whilenodeCount>0:node=queue.pop(0)print(node.data,end=" ")ifnode.leftisnotNone:queue.append(node.left)ifnode.rightisnotNone:queue.append(node.right)nodeCount-=1print()if__name__=="__main__":# Make a binary tree## 1# / \# 2 3# / \# 4 5 root=Node(1)root.left=Node(2)root.right=Node(3)root.right.left=Node(4)root.right.right=Node(5)root=flipBinaryTree(root)printLevelOrder(root)
C#
// C# program to flip a binary tree // using recursionusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Method to flip the binary treestaticNodeFlipBinaryTree(Noderoot){if(root==null)returnroot;if(root.left==null&&root.right==null)returnroot;// Recursively call the same methodNodeflippedRoot=FlipBinaryTree(root.left);// Rearranging main root Node after returning// from recursive callroot.left.left=root.right;root.left.right=root;root.left=root.right=null;returnflippedRoot;}// Iterative method to do level order // traversal line by linestaticvoidPrintLevelOrder(Noderoot){if(root==null)return;// Create an empty queue for level // order traversalQueue<Node>q=newQueue<Node>();// Enqueue Root and initialize heightq.Enqueue(root);while(q.Count>0){// nodeCount (queue size) indicates // number of nodes at current levelintnodeCount=q.Count;// Dequeue all nodes of current level // and Enqueue all nodes of next levelwhile(nodeCount>0){Nodenode=q.Dequeue();Console.Write(node.data+" ");if(node.left!=null)q.Enqueue(node.left);if(node.right!=null)q.Enqueue(node.right);nodeCount--;}Console.WriteLine();}}staticvoidMain(string[]args){// Make a binary tree//// 1// / \// 2 3// / \// 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);root=FlipBinaryTree(root);PrintLevelOrder(root);}}
JavaScript
// JavaScript program to flip a binary // tree using recursionclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}// Method to flip the binary treefunctionflipBinaryTree(root){if(root===null)returnroot;if(root.left===null&&root.right===null)returnroot;// Recursively call the same methodconstflippedRoot=flipBinaryTree(root.left);// Rearranging main root Node after returning// from recursive callroot.left.left=root.right;root.left.right=root;root.left=root.right=null;returnflippedRoot;}// Iterative method to do level order traversal// line by linefunctionprintLevelOrder(root){if(root===null)return;// Create an empty queue for level// order traversalconstqueue=[root];while(queue.length>0){letnodeCount=queue.length;while(nodeCount>0){constnode=queue.shift();console.log(node.data+" ");if(node.left!==null)queue.push(node.left);if(node.right!==null)queue.push(node.right);nodeCount--;}console.log();}}// Make a binary tree//// 1// / \// 2 3// / \// 4 5 constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);constflippedRoot=flipBinaryTree(root);printLevelOrder(flippedRoot);
Output
2
3 1
4 5
[Expected Approach - 2] Iterative Approach - O(n) Time and O(n) Space
The iterative solution follows the same approach as the recursive one, the only thing we need to pay attention to is saving the node information that will be overwritten.
Below is the implementation of the above approach:
C++
// C++ program to flip a binary tree using// iterative approach#include<bits/stdc++.h>usingnamespacestd;classNode{public:intdata;Node*left,*right;Node(intx){data=x;left=right=nullptr;}};// Method to flip the binary tree iterativelyNode*flipBinaryTree(Node*root){// intiliazing the pointers to do the // swapping and storing statesNode*curr=root,*next=nullptr,*prev=nullptr,*ptr=nullptr;while(curr!=nullptr){// pointing the next pointer to the// current next of leftnext=curr->left;// making the right child of prev // as curr left childcurr->left=ptr;// storign the right child of// curr in tempptr=curr->right;curr->right=prev;prev=curr;curr=next;}returnprev;}// Iterative method to do level order traversal// line by linevoidprintLevelOrder(Node*root){// Base Caseif(root==nullptr)return;// Create an empty queue for level // order traversalqueue<Node*>q;// Enqueue Root and // initialize heightq.push(root);while(1){// nodeCount (queue size) indicates number// of nodes at current level.intnodeCount=q.size();if(nodeCount==0)break;// Dequeue all nodes of current level and// Enqueue all nodes of next levelwhile(nodeCount>0){Node*node=q.front();cout<<node->data<<" ";q.pop();if(node->left!=nullptr)q.push(node->left);if(node->right!=nullptr)q.push(node->right);nodeCount--;}cout<<endl;}}intmain(){// Make a binary tree//// 1// / \ // 2 3// / \ // 4 5 Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->right->left=newNode(4);root->right->right=newNode(5);root=flipBinaryTree(root);printLevelOrder(root);return0;}
Java
// Java program to flip a binary tree// using iterative approachclassNode{intdata;Nodeleft,right;Node(intx){data=x;left=right=null;}}classGfG{// Method to flip the binary treestaticNodeflipBinaryTree(Noderoot){// Initializing the pointers to do the // swapping and storing statesNodecurr=root;Nodenext=null;Nodeprev=null;Nodeptr=null;while(curr!=null){// Pointing the next pointer to// the current next of leftnext=curr.left;// Making the right child of // prev as curr left childcurr.left=ptr;// Storing the right child // of curr in ptrptr=curr.right;curr.right=prev;prev=curr;curr=next;}returnprev;}// Iterative method to do level order// traversal line by linestaticvoidprintLevelOrder(Noderoot){if(root==null)return;// Create an empty queue for level // order traversaljava.util.Queue<Node>q=newjava.util.LinkedList<>();// Enqueue Root and initialize // heightq.add(root);while(!q.isEmpty()){// nodeCount (queue size) indicates // number of nodes at current levelintnodeCount=q.size();// Dequeue all nodes of current level // and Enqueue all nodes of next levelwhile(nodeCount>0){Nodenode=q.poll();System.out.print(node.data+" ");if(node.left!=null)q.add(node.left);if(node.right!=null)q.add(node.right);nodeCount--;}System.out.println();}}publicstaticvoidmain(String[]args){// Make a binary tree//// 1// / \// 2 3// / \// 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);root=flipBinaryTree(root);printLevelOrder(root);}}
Python
# Python program to flip a binary tree# using iterative approachclassNode:def__init__(self,x):self.data=xself.left=Noneself.right=None# Method to flip the binary tree# iterativelydefflip_binary_tree(root):# Initializing the pointers to do# the swapping and storing statescurr=rootnext=Noneprev=Noneptr=NonewhilecurrisnotNone:# Pointing the next pointer to the# current next of leftnext=curr.left# Making the right child of prev# as curr left childcurr.left=ptr# Storing the right child of# curr in ptrptr=curr.rightcurr.right=prevprev=currcurr=nextreturnprev# Iterative method to do level order# traversal line by linedefprintLevelOrder(root):ifrootisNone:return# Create an empty queue for# level order traversalqueue=[]queue.append(root)whilequeue:nodeCount=len(queue)whilenodeCount>0:node=queue.pop(0)print(node.data,end=" ")ifnode.leftisnotNone:queue.append(node.left)ifnode.rightisnotNone:queue.append(node.right)nodeCount-=1print()if__name__=="__main__":# Make a binary tree## 1# / \# 2 3# / \# 4 5root=Node(1)root.left=Node(2)root.right=Node(3)root.right.left=Node(4)root.right.right=Node(5)root=flip_binary_tree(root)printLevelOrder(root)
C#
// C# program to flip a binary tree// using iterative approachusingSystem;usingSystem.Collections.Generic;classNode{publicintdata;publicNodeleft,right;publicNode(intx){data=x;left=right=null;}}classGfG{// Method to flip the binary treestaticNodeFlipBinaryTree(Noderoot){// Initializing the pointers to // do the swapping and storing statesNodecurr=root;Nodenext=null;Nodeprev=null;Nodeptr=null;while(curr!=null){// Pointing the next pointer to // the current next of leftnext=curr.left;// Making the right child of prev// as curr left childcurr.left=ptr;// Storing the right child// of curr in ptrptr=curr.right;curr.right=prev;prev=curr;curr=next;}returnprev;}// Iterative method to do level order// traversal line by linestaticvoidPrintLevelOrder(Noderoot){if(root==null)return;// Create an empty queue for// level order traversalQueue<Node>q=newQueue<Node>();// Enqueue Root and initialize heightq.Enqueue(root);while(q.Count>0){// nodeCount (queue size) indicates // number of nodes at current levelintnodeCount=q.Count;// Dequeue all nodes of current level // and Enqueue all nodes of next levelwhile(nodeCount>0){Nodenode=q.Dequeue();Console.Write(node.data+" ");if(node.left!=null)q.Enqueue(node.left);if(node.right!=null)q.Enqueue(node.right);nodeCount--;}Console.WriteLine();}}staticvoidMain(string[]args){// Make a binary tree//// 1// / \// 2 3// / \// 4 5 Noderoot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);root=FlipBinaryTree(root);PrintLevelOrder(root);}}
JavaScript
// JavaScript program to flip a binary // tree using iterative approachclassNode{constructor(x){this.data=x;this.left=null;this.right=null;}}functionflipBinaryTree(root){// Initializing the pointers to do the// swapping and storing statesletcurr=root;letnext=null;letprev=null;letptr=null;while(curr!==null){// Pointing the next pointer to the // current next of leftnext=curr.left;// Making the right child of prev// as curr left childcurr.left=ptr;// Storing the right child of // curr in ptrptr=curr.right;curr.right=prev;prev=curr;curr=next;}returnprev;}// Iterative method to do level order// traversal line by linefunctionprintLevelOrder(root){if(root===null)return;// Create an empty queue for// level order traversalconstqueue=[root];while(queue.length>0){letnodeCount=queue.length;while(nodeCount>0){constnode=queue.shift();console.log(node.data+" ");if(node.left!==null)queue.push(node.left);if(node.right!==null)queue.push(node.right);nodeCount--;}console.log();}}// Make a binary tree//// 1// / \// 2 3// / \// 4 5 constroot=newNode(1);root.left=newNode(2);root.right=newNode(3);root.right.left=newNode(4);root.right.right=newNode(5);constflippedRoot=flipBinaryTree(root);printLevelOrder(flippedRoot);
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.