The Wayback Machine - https://web.archive.org/web/20241006121643/https://www.geeksforgeeks.org/flip-binary-tree/
Open In App

Flip Binary Tree

Last Updated : 02 May, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

A Given a binary tree, the task is to flip the binary tree towards the right direction that is clockwise. See the below examples to see the transformation.

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 left most nodes recursively. 

tree1

tree2

Below is the main rotation code of a subtree 

    root->left->left = root->right;
    root->left->right = root;
    root->left = NULL;
    root->right = NULL; 

The above code can be understood by the following diagram – 

tree4

As we are storing root->left in the flipped root, flipped subtree gets stored in each recursive call.

Implementation:

C++




/*  C/C++ program to flip a binary tree */
#include <bits/stdc++.h>
using namespace std;
 
/* A binary tree node structure */
struct Node
{
    int data;
    Node *left, *right;
};
 
/* Utility function to create a new Binary
   Tree Node */
struct Node* newNode(int data)
{
    struct Node *temp = new struct Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// method to flip the binary tree
Node* flipBinaryTree(Node* root)
{
    // Base cases
    if (root == NULL)
        return root;
    if (root->left == NULL && root->right == NULL)
        return root;
 
    //  recursively call the same method
    Node* flippedRoot = flipBinaryTree(root->left);
 
    //  rearranging main root Node after returning
    // from recursive call
    root->left->left = root->right;
    root->left->right = root;
    root->left = root->right = NULL;
 
    return flippedRoot;
}
 
// Iterative method to do level order traversal
// line by line
void printLevelOrder(Node *root)
{
    // Base Case
    if (root == NULL)  return;
 
    // Create an empty queue for level order traversal
    queue<Node *> q;
 
    // Enqueue Root and initialize height
    q.push(root);
 
    while (1)
    {
        // nodeCount (queue size) indicates number
        // of nodes at current level.
        int nodeCount = q.size();
        if (nodeCount == 0)
            break;
 
        // Dequeue all nodes of current level and
        // Enqueue all nodes of next level
        while (nodeCount > 0)
        {
            Node *node = q.front();
            cout << node->data << " ";
            q.pop();
            if (node->left != NULL)
                q.push(node->left);
            if (node->right != NULL)
                q.push(node->right);
            nodeCount--;
        }
        cout << endl;
    }
}
 
//  Driver code
int main()
{
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->right->left = newNode(4);
    root->right->right = newNode(5);
 
    cout << "Level order traversal of given tree\n";
    printLevelOrder(root);
 
    root = flipBinaryTree(root);
 
    cout << "\nLevel order traversal of the flipped"
            " tree\n";
    printLevelOrder(root);
    return 0;
}


Java




/*  Java program to flip a binary tree */
import java.util.Queue;
import java.util.LinkedList;
public class FlipTree {
 
    // method to flip the binary tree
    public static Node flipBinaryTree(Node root)
    {
        if (root == null)
            return root;
        if (root.left == null && root.right ==null)
            return root;
 
        //  recursively call the same method
        Node flippedRoot=flipBinaryTree(root.left);
 
        //  rearranging main root Node after returning
        // from recursive call
        root.left.left=root.right;
        root.left.right=root;
        root.left=root.right=null;
        return flippedRoot;
    }
 
    // Iterative method to do level order traversal
    // line by line
    public static void printLevelOrder(Node root)
    {
        // Base Case
        if(root==null)
            return ;
         
        // Create an empty queue for level order traversal
        Queue<Node> q=new LinkedList<>();
        // Enqueue Root and initialize height
        q.add(root);
        while(true)
        {
            // nodeCount (queue size) indicates number
            // of nodes at current level.
            int nodeCount = q.size();
            if (nodeCount == 0)
                break;
             
            // Dequeue all nodes of current level and
            // Enqueue all nodes of next level
            while (nodeCount > 0)
            {
                Node node = q.remove();
                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();
        }
    }
 
    public static void main(String args[]) {
        Node root=new Node(1);
        root.left=new Node(2);
        root.right=new Node(1);
        root.right.left = new Node(4);
        root.right.right = new Node(5);
        System.out.println("Level order traversal of given tree");
        printLevelOrder(root);
   
        root = flipBinaryTree(root);
        System.out.println("Level order traversal of flipped tree");
        printLevelOrder(root);
    }
}
 
/* A binary tree node structure */
class Node
{
    int data;
    Node left, right;
    Node(int data)
    {
        this.data=data;
    }
};
 
//This code is contributed by Gaurav Tiwari


Python3




# Python3 program to flip
# a binary tree
 
# A binary tree node
class Node:
     
    # Constructor to create
    # a new node
    def __init__(self, data):
       
        self.data = data
        self.right = None
        self.left = None
 
def flipBinaryTree(root):
     
    # Base Cases
    if root is None:
        return root
     
    if (root.left is None and
        root.right is None):
        return root
 
    # Recursively call the
    # same method
    flippedRoot = flipBinaryTree(root.left)
 
    # Rearranging main root Node
    # after returning from
    # recursive call
    root.left.left = root.right
    root.left.right = root
    root.left = root.right = None
 
    return flippedRoot
 
# Iterative method to do the level
# order traversal line by line
def printLevelOrder(root):
     
    # Base Case
    if root is None:
        return
     
    # Create an empty queue for
    # level order traversal
    from Queue import Queue
    q = Queue()
     
    # Enqueue root and initialize
    # height
    q.put(root)
     
    while(True):
 
        # nodeCount (queue size) indicates
        # number of nodes at current level
        nodeCount = q.qsize()
        if nodeCount == 0:
            break
 
        # Dequeue all nodes of current
        # level and Enqueue all nodes
        # of next level  
        while nodeCount > 0:
            node = q.get()
            print(node.data, end=" ")
            if node.left is not None:
                q.put(node.left)
            if node.right is not None:
                q.put(node.right)
            nodeCount -= 1
 
        print
         
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.right.left = Node(4)
root.right.right = Node(5)
 
print("Level order traversal of given tree")
printLevelOrder(root)
 
root = flipBinaryTree(root)
 
print("\nLevel order traversal of the flipped tree")
printLevelOrder(root)
 
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)


C#




// C# program to flip a binary tree
using System;
using System.Collections.Generic;
 
public class FlipTree
{
 
    // method to flip the binary tree
    public static Node flipBinaryTree(Node root)
    {
        if (root == null)
            return root;
        if (root.left == null && root.right ==null)
            return root;
 
        // recursively call the same method
        Node flippedRoot = flipBinaryTree(root.left);
 
        // rearranging main root Node after returning
        // from recursive call
        root.left.left = root.right;
        root.left.right = root;
        root.left = root.right = null;
        return flippedRoot;
    }
 
    // Iterative method to do level order traversal
    // line by line
    public static void printLevelOrder(Node root)
    {
        // Base Case
        if(root == null)
            return ;
         
        // Create an empty queue for level order traversal
        Queue<Node> q = new Queue<Node>();
         
        // Enqueue Root and initialize height
        q.Enqueue(root);
        while(true)
        {
            // nodeCount (queue size) indicates number
            // of nodes at current level.
            int nodeCount = q.Count;
            if (nodeCount == 0)
                break;
             
            // Dequeue all nodes of current level and
            // Enqueue all nodes of next level
            while (nodeCount > 0)
            {
                Node node = 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();
        }
    }
 
    // Driver code
    public static void Main(String []args)
    {
        Node root = new Node(1);
        root.left = new Node(2);
        root.right = new Node(1);
        root.right.left = new Node(4);
        root.right.right = new Node(5);
        Console.WriteLine("Level order traversal of given tree");
        printLevelOrder(root);
     
        root = flipBinaryTree(root);
        Console.WriteLine("Level order traversal of flipped tree");
        printLevelOrder(root);
    }
}
 
/* A binary tree node structure */
public class Node
{
    public int data;
    public Node left, right;
    public Node(int data)
    {
        this.data = data;
    }
};
 
// This code is contributed by Princi Singh


Javascript




<script>
/*  Javascript program to flip a binary tree */
     
    /* A binary tree node structure */
    class Node
    {
         
        constructor( data)
        {
            this.data = data;
            this.left=this.right=null;
        }
    };
     
    // method to flip the binary tree
    function flipBinaryTree(root)
    {
         if (root == null)
            return root;
        if (root.left == null && root.right ==null)
            return root;
  
        //  recursively call the same method
        let flippedRoot=flipBinaryTree(root.left);
  
        //  rearranging main root Node after returning
        // from recursive call
        root.left.left=root.right;
        root.left.right=root;
        root.left=root.right=null;
        return flippedRoot;
    }
     
    // Iterative method to do level order traversal
    // line by line
    function printLevelOrder(root)
    {
        // Base Case
        if(root==null)
            return ;
          
        // Create an empty queue for level order traversal
        let q=[];
        // Enqueue Root and initialize height
        q.push(root);
        while(true)
        {
            // nodeCount (queue size) indicates number
            // of nodes at current level.
            let nodeCount = q.length;
            if (nodeCount == 0)
                break;
              
            // Dequeue all nodes of current level and
            // Enqueue all nodes of next level
            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("<br>");
        }
    }
     
    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("Level order traversal of given tree<br>");
        printLevelOrder(root);
    
        root = flipBinaryTree(root);
        document.write("Level order traversal of flipped tree<br>");
        printLevelOrder(root);
     
     
    // This code is contributed by unknown2108
</script>


Output

Level order traversal of given tree
1 
2 3 
4 5 

Level order traversal of the flipped tree
2 
3 1 
4 5 

Time Complexity: O(n), where n is the number of nodes in the given binary tree.
Auxiliary Space: O(n), the size of the queue can grow up to n.

Iterative Approach: This approach is contributed by Pal13. 
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. 

Implementation:

C++




//  C/C++ program to flip a binary tree
#include <bits/stdc++.h>
using namespace std;
 
// A binary tree node structure
struct Node
{
    int data;
    Node *left, *right;
};
 
// Utility function to create a new Binary
// Tree Node
struct Node* newNode(int data)
{
    struct Node *temp = new struct Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// method to flip the binary tree
Node* flipBinaryTree(Node* root)
{
    // Initialization of pointers
    Node *curr = root;
    Node *next = NULL;
    Node *temp = NULL;
    Node *prev = NULL;
     
    // Iterate through all left nodes
    while(curr)
    {
        next = curr->left;
         
        // Swapping nodes now, need temp to keep the previous right child
         
        // Making prev's right as curr's left child
        curr->left = temp;        
         
        // Storing curr's right child
        temp = curr->right;        
         
        // Making prev as curr's right child
        curr->right = prev;        
         
        prev = curr;
        curr = next;
    }
    return prev;
}
 
// Iterative method to do level order traversal
// line by line
void printLevelOrder(Node *root)
{
    // Base Case
    if (root == NULL) return;
 
    // Create an empty queue for level order traversal
    queue<Node *> q;
 
    // Enqueue Root and initialize height
    q.push(root);
 
    while (1)
    {
        // nodeCount (queue size) indicates number
        // of nodes at current level.
        int nodeCount = q.size();
        if (nodeCount == 0)
            break;
 
        // Dequeue all nodes of current level and
        // Enqueue all nodes of next level
        while (nodeCount > 0)
        {
            Node *node = q.front();
            cout << node->data << " ";
            q.pop();
             
            if (node->left != NULL)
                q.push(node->left);
             
            if (node->right != NULL)
                q.push(node->right);
            nodeCount--;
        }
        cout << endl;
    }
}
 
// Driver code
int main()
{
     
    Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->right->left = newNode(4);
    root->right->right = newNode(5);
 
    cout << "Level order traversal of given tree\n";
    printLevelOrder(root);
 
    root = flipBinaryTree(root);
 
    cout << "\nLevel order traversal of the flipped"
            " tree\n";
    printLevelOrder(root);
    return 0;
}
 
// This article is contributed by Pal13


Java




// Java program to flip a binary tree
import java.util.*;
class GFG
{
     
// A binary tree node
static class Node
{
    int data;
    Node left, right;
};
 
// Utility function to create
// a new Binary Tree Node
 
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// method to flip the binary tree
static Node flipBinaryTree(Node root)
{
    // Initialization of pointers
    Node curr = root;
    Node next = null;
    Node temp = null;
    Node prev = null;
     
    // Iterate through all left nodes
    while(curr != null)
    {
        next = curr.left;
         
        // Swapping nodes now, need
        // temp to keep the previous
        // right child
         
        // Making prev's right
        // as curr's left child
        curr.left = temp;        
         
        // Storing curr's right child
        temp = curr.right;        
         
        // Making prev as curr's
        // right child
        curr.right = prev;        
         
        prev = curr;
        curr = next;
    }
    return prev;
}
 
// Iterative method to do
// level order traversal
// line by line
static void printLevelOrder(Node root)
{
    // Base Case
    if (root == null) return;
 
    // Create an empty queue for
    // level order traversal
    Queue<Node> q = new LinkedList<Node>();
 
    // Enqueue Root and
    // initialize height
    q.add(root);
 
    while (true)
    {
        // nodeCount (queue size)
        // indicates number of nodes
        // at current level.
        int nodeCount = q.size();
        if (nodeCount == 0)
            break;
 
        // Dequeue all nodes of current
        // level and Enqueue all nodes
        // of next level
        while (nodeCount > 0)
        {
            Node node = q.peek();
            System.out.print(node.data + " ");
            q.remove();
             
            if (node.left != null)
                q.add(node.left);
             
            if (node.right != null)
                q.add(node.right);
            nodeCount--;
        }
        System.out.println();
    }
}
 
// Driver code
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);
 
    System.out.print("Level order traversal " +
                            "of given tree\n");
    printLevelOrder(root);
 
    root = flipBinaryTree(root);
 
    System.out.print("\nLevel order traversal " +
                        "of the flipped tree\n");
    printLevelOrder(root);
}
}
 
// This code is contributed
// by Arnab Kundu


Python3




# Python3 program to flip
# a binary tree
from collections import deque
 
# A binary tree node structure
class Node:
   
    def __init__(self, key):
       
        self.data = key
        self.left = None
        self.right = None
 
# method to flip the
# binary tree
def flipBinaryTree(root):
   
    # Initialization of
    # pointers
    curr = root
    next = None
    temp = None
    prev = None
 
    # Iterate through all
    # left nodes
    while(curr):
        next = curr.left
 
        # Swapping nodes now, need temp
        # to keep the previous right child
 
        # Making prev's right as curr's
        # left child
        curr.left = temp
 
        # Storing curr's right child
        temp = curr.right
 
        # Making prev as curr's right
        # child
        curr.right = prev
 
        prev = curr
        curr = next
    return prev
 
# Iterative method to do level
# order traversal line by line
def printLevelOrder(root):
   
    # Base Case
    if (root == None):
        return
 
    # Create an empty queue for
    # level order traversal
    q = deque()
 
    # Enqueue Root and initialize
    # height
    q.append(root)
 
    while (1):
        # nodeCount (queue size) indicates
        # number of nodes at current level.
        nodeCount = len(q)
        if (nodeCount == 0):
            break
 
        # Dequeue all nodes of current
        # level and Enqueue all nodes
        # of next level
        while (nodeCount > 0):
            node = q.popleft()
            print(node.data, end = " ")
 
            if (node.left != None):
                q.append(node.left)
 
            if (node.right != None):
                q.append(node.right)
            nodeCount -= 1
 
        print()
 
# Driver code
if __name__ == '__main__':
   
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.right.left = Node(4)
    root.right.right = Node(5)
 
    print("Level order traversal of given tree")
    printLevelOrder(root)
 
    root = flipBinaryTree(root)
 
    print("\nLevel order traversal of the flipped"
          " tree")
    printLevelOrder(root)
 
# This code is contributed by Mohit Kumar 29


C#




// C# program to flip a binary tree
using System;
using System.Collections.Generic;
 
class GFG
{
 
// A binary tree node
public class Node
{
    public int data;
    public Node left, right;
}
 
// Utility function to create
// a new Binary Tree Node
public static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.left = temp.right = null;
    return temp;
}
 
// method to flip the binary tree
public static Node flipBinaryTree(Node root)
{
    // Initialization of pointers
    Node curr = root;
    Node next = null;
    Node temp = null;
    Node prev = null;
 
    // Iterate through all left nodes
    while (curr != null)
    {
        next = curr.left;
 
        // Swapping nodes now, need
        // temp to keep the previous
        // right child
 
        // Making prev's right
        // as curr's left child
        curr.left = temp;
 
        // Storing curr's right child
        temp = curr.right;
 
        // Making prev as curr's
        // right child
        curr.right = prev;
 
        prev = curr;
        curr = next;
    }
    return prev;
}
 
// Iterative method to do level
// order traversal line by line
public static void printLevelOrder(Node root)
{
    // Base Case
    if (root == null)
    {
        return;
    }
 
    // Create an empty queue for
    // level order traversal
    LinkedList<Node> q = new LinkedList<Node>();
 
    // Enqueue Root and
    // initialize height
    q.AddLast(root);
 
    while (true)
    {
        // nodeCount (queue size)
        // indicates number of nodes
        // at current level.
        int nodeCount = q.Count;
        if (nodeCount == 0)
        {
            break;
        }
 
        // Dequeue all nodes of current
        // level and Enqueue all nodes
        // of next level
        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();
    }
}
 
// Driver code
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\n");
    printLevelOrder(root);
 
    root = flipBinaryTree(root);
 
    Console.Write("\nLevel order traversal " +
                     "of the flipped tree\n");
    printLevelOrder(root);
}
}
 
// This code is contributed by Shrikant13


Javascript




<script>
 
    // JavaScript program to flip a binary tree
     
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
     
    // Utility function to create
    // a new Binary Tree Node
 
    function newNode(data)
    {
        let temp = new Node(data);
        return temp;
    }
 
    // method to flip the binary tree
    function flipBinaryTree(root)
    {
        // Initialization of pointers
        let curr = root;
        let next = null;
        let temp = null;
        let prev = null;
 
        // Iterate through all left nodes
        while(curr != null)
        {
            next = curr.left;
 
            // Swapping nodes now, need
            // temp to keep the previous
            // right child
 
            // Making prev's right
            // as curr's left child
            curr.left = temp;       
 
            // Storing curr's right child
            temp = curr.right;       
 
            // Making prev as curr's
            // right child
            curr.right = prev;       
 
            prev = curr;
            curr = next;
        }
        return prev;
    }
 
    // Iterative method to do
    // level order traversal
    // line by line
    function printLevelOrder(root)
    {
        // Base Case
        if (root == null) return;
 
        // Create an empty queue for
        // level order traversal
        let q = [];
 
        // Enqueue Root and
        // initialize height
        q.push(root);
 
        while (true)
        {
            // nodeCount (queue size)
            // indicates number of nodes
            // at current level.
            let nodeCount = q.length;
            if (nodeCount == 0)
                break;
 
            // Dequeue all nodes of current
            // level and Enqueue all nodes
            // of next level
            while (nodeCount > 0)
            {
                let node = q[0];
                document.write(node.data + " ");
                q.shift();
 
                if (node.left != null)
                    q.push(node.left);
 
                if (node.right != null)
                    q.push(node.right);
                nodeCount--;
            }
            document.write("</br>");
        }
    }
     
    let root = newNode(1);
    root.left = newNode(2);
    root.right = newNode(3);
    root.right.left = newNode(4);
    root.right.right = newNode(5);
  
    document.write("Level order traversal " +
                            "of given tree" + "</br>");
    printLevelOrder(root);
  
    root = flipBinaryTree(root);
  
    document.write("</br>" + "Level order traversal " +
                        "of the flipped tree" + "</br>");
    printLevelOrder(root);
 
</script>


Output

Level order traversal of given tree
1 
2 3 
4 5 

Level order traversal of the flipped tree
2 
3 1 
4 5 

Complexity Analysis: 

  • Time complexity: O(n) as in the worst case, depth of binary tree will be n. 
  • Auxiliary Space: O(1).


Previous Article
Next Article

Similar Reads

Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Minimum flip required to make Binary Matrix symmetric
Given a Binary Matrix of size N X N, consisting of 1s and 0s. The task is to find the minimum flips required to make the matrix symmetric along main diagonal.Examples : Input : mat[][] = { { 0, 0, 1 }, { 1, 1, 1 }, { 1, 0, 0 } }; Output : 2 Value of mat[1][0] is not equal to mat[0][1]. Value of mat[2][1] is not equal to mat[1][2]. So, two flip are
10 min read
Minimum flips required to form given binary string where every flip changes all bits to its right as well
Given a string S, the task is to find minimum flips required to convert an initial binary string consisting of only zeroes to S where every flip of a character flips all succeeding characters as well. Examples: Input: S = "01011" Output: 3 Explanation: Initial String - "00000" Flip the 2nd bit - "01111" Flip the 3rd bit - "01000" Flip the 4th bit -
4 min read
Queries to flip characters of a binary string in given range
Given a binary string, str and a 2D array Q[][] representing queries of the form {L, R}. In each query, toggle all the characters of the binary strings present in the indices [L, R]. The task is to print the binary string by performing all the queries. Examples: Input: str = "101010", Q[][] = { {0, 1}, {2, 5}, {2, 3}, {1, 4}, {0, 5} } Output: 11100
8 min read
Flip all 0s in given Binary Strings K times with different neighbours
Given a binary string S of size N and a positive integer K, the task is to repeatedly modify the given string K number of times by flipping all the 0s having different adjacent characters in each iteration. Note: For the character 0 present at 0th index then it will change to 1 only when 1st index character is 1 and if the last index character is 0
8 min read
Find the last player to be able to flip a character in a Binary String
Given a binary string S of length N, the task is to find the winner of the game if two players A and B plays optimally as per the following rules: Player A always starts the game.In a player's first turn, he can move to any index (1-based indexing) consisting of '0' and make it '1'.For the subsequent turns, if any player is at index i, then he can
10 min read
Minimize Suffix flip to make Binary String non decreasing
Given a binary string str, the task is to find the minimum operations required to convert the binary string in a non-decreasing manner such that in each operation an index i is chosen and all bits right to it are flipped. Examples: Input: str = "100010"Output: 3Explanation: On flipping at index 0 it becomes 111101. On flipping at the index at index
7 min read
Horizontally Flip a Binary Matrix
Given a binary matrix. The task is to flip the matrix horizontally(find the image of the matrix), then invert it. Note: To flip a matrix horizontally means reversing each row of the matrix. For example, flipping [1, 1, 0, 0] horizontally results in [0, 0, 1, 1].To invert a matrix means replacing each 0 by 1 and vice-versa. For example, inverting [0
9 min read
Find longest sequence of 1's in binary representation with one flip
Give an integer n. We can flip exactly one bit. Write code to find the length of the longest sequence of 1 s you could create. Examples: Input : 1775 Output : 8 Binary representation of 1775 is 11011101111.After flipping the highlighted bit, we get consecutive 8 bits. 11011111111.Input : 12 Output : 3 Input : 15Output : 5Input : 71Output: 4Binary r
12 min read
Count Number of Distinct Binary Strings After Applying Flip Operations
Given a binary string s and a positive integer k. In a operation you can repeatedly choose any substring of length k in s and flip all its characters (0s to 1s, 1s to 0s). The task is to return the number of distinct strings that can be obtained, modulo 10^9 + 7. You can perform the flip operation any number of times. Example: Input: s = "1001", k
5 min read
Convert a Generic Tree(N-array Tree) to Binary Tree
Prerequisite: Generic Trees(N-array Trees) In this article, we will discuss the conversion of the Generic Tree to a Binary Tree. Following are the rules to convert a Generic(N-array Tree) to a Binary Tree: The root of the Binary Tree is the Root of the Generic Tree.The left child of a node in the Generic Tree is the Left child of that node in the B
13 min read
Convert a Binary Tree to Threaded binary tree | Set 1 (Using Queue)
We have discussed Threaded Binary Tree. The idea of threaded binary trees is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. The following diagram sho
12 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Check whether a given binary tree is skewed binary tree or not?
Given a Binary Tree check whether it is skewed binary tree or not. A skewed tree is a tree where each node has only one child node or none. Examples: Input : 5 / 4 \ 3 / 2 Output : Yes Input : 5 / 4 \ 3 / \ 2 4 Output : No The idea is to check if a node has two children. If node has two children return false, else recursively compute whether subtre
13 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Check if a Binary tree is Subtree of another Binary tree | Set 3
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree-T Tree-S 1 3 / \ / 2
15 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Check if a binary tree is subtree of another binary tree | Set 2
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree.For example, in the following case, Tree1 i
15+ min read
Minimum swap required to convert binary tree to binary search tree
Given the array representation of Complete Binary Tree i.e, if index i is the parent, index 2*i + 1 is the left child and index 2*i + 2 is the right child. The task is to find the minimum number of swap required to convert it into Binary Search Tree. Examples: Input : arr[] = { 5, 6, 7, 8, 9, 10, 11 } Output : 3 Binary tree of the given array: Swap
8 min read
Convert a Binary Tree to Threaded binary tree | Set 2 (Efficient)
Idea of Threaded Binary Tree is to make inorder traversal faster and do it without stack and without recursion. In a simple threaded binary tree, the NULL right pointers are used to store inorder successor. Wherever a right pointer is NULL, it is used to store inorder successor. Following diagram shows an example Single Threaded Binary Tree. The do
12 min read
Check if a Binary Tree is subtree of another binary tree | Set 1
Given two binary trees, check if the first tree is a subtree of the second one. A subtree of a tree T is a tree S consisting of a node in T and all of its descendants in T. The subtree corresponding to the root node is the entire tree; the subtree corresponding to any other node is called a proper subtree. Examples: Input: Tree S 10 / \ 4 6 \ 30 Tr
11 min read
Difference between Binary Tree and Binary Search Tree
Binary Tree Data Structure:A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right children. Binary Search Tree Data Structure (BST):A binary search tree is a hierarchical data structure where each node has at most two children, wi
2 min read
Binary Tree to Binary Search Tree Conversion
Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. Examples Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree. Approach: The idea to recursively trav
7 min read
Binary Tree to Binary Search Tree Conversion using STL set
Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. Example: Input: Output: Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree. Approach: The idea is to recursively t
7 min read
Flip minimum signs of array elements to get minimum sum of positive elements possible
Given an array of positive elements, you have to flip the sign of some of its elements such that the resultant sum of the elements of array should be minimum non-negative (as close to zero as possible). Return the minimum no. of elements whose sign needs to be flipped such that the resultant sum is minimum non-negative. Note that the sum of all the
12 min read
Sand Timer Flip Counting Problem
Given two integers A and B representing the time taken by two different Sand timers to get empty. The task is to find the count of flips of each timer till the instance at which both the Sand timers get empty at the same time.Examples: Input: A = 30, B = 15 Output: 0 1 After 15 minutes: 15 0 Flip timer 2: 15 15 After another 15 minutes: 0 0Input: A
4 min read
Flip consecutive set bits starting from LSB of a given number
Given a positive integer N, the task is to find the number that can be obtained by flipping consecutive set bits starting from the LSB in the binary representation of N. Examples: Input: N = 39Output: 32Explanation:Binary representation of (39)10 = (100111)2After flipping all consecutive set bits starting from the LSB, the number obtained is (10000
6 min read
Flip bits of the sum of count of set bits of two given numbers
Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum. Examples: Input: A = 5, B = 7Output: 2Explanation:Binary representation of A is 101.Binary representation of B is 111.Count of set bits in A and B = 2 + 3 = 5.Binary representation of the sum obtained = 101Flipping the bits of th
5 min read
Flip all K-bits of a given number
Given two integers N and K, the task is to represent N in K bits and print the number obtained after flipping all the bits. Examples: Input:N = 1, K = 32Output: 4294967294Explanation:1 in K(= 32) bit representation is (00000000000000000000000000000001)2.Flipping all the bits modifies N to (11111111111111111111111111111110)2 = (4294967294)10. Input:
3 min read
Flip the String by either swapping given characters or rotating it horizontally for Q queries
Given a string S of length 2N and Q Queries containing three integers T, A, and B each, where queries can be of the following two types: T=1: Swap the Ath and Bth characters in S.(In 1-based indexing)T=2: Swap the first N characters with the last N characters i.e "ABCD" becomes "CDAB" The task is to find the final string after applying the Q Querie
15 min read
Article Tags :
Practice Tags :