Skip to main content

Invert a Binary Tree – Recursive and Iterative Approach in Java Vijay Sinha The Crazy Programmer

In this article we have a look at another interesting problem related to binary tree. Given a binary tree we have to invert the tree and print it. We discuss different approaches to solve this problem along with their time and space complexities

The inversion of a binary tree or the invert of a binary tree means to convert the tree into it’s Mirror image. In simple terms, it is a tree whose left children and right children of all non-leaf nodes are swapped.

Note: The leaf nodes will also get interchanged. It is recommended to learn In-Order and Post Order traversal before proceeding with this problem.

Let us look at an example of a binary tree:

Invert a Binary Tree

 

In the above figure we see the sample tree and it’s inverted or mirror version.

Input:             20                                                  
                /       \
               /         \
              10          30                      
            /   \        /   \
           /     \      /     \
          5      15    25      35                


Output:            20                                                  
                /       \
               /         \
              30          10                      
            /   \        /   \
           /     \      /     \
          35      25   5      15

Approach 1 (Recursive Approach)

Follow these steps:

  • We basically do a Post-Order Traversal of our tree starting from the root where we traverse for the left subtree first and then the right subtree before processing the root.
  • At time of processing the root of each node we swap their left and right child respectively if their children are not null.
  • We also check if the given root of binary tree is null or not. Then, we continue traversing for the left and right subtrees accordingly. If, we are at a leaf node it does not have any children for which we return null indicating that no swapping is required.
  • To verify the tree is inverted or not we do the In-Order traversal of tree before executing the function and again print the In-Order traversal after doing inversion. You can verify the output using any traversal algorithm.

Now, let’s look at the implementation of above in code:

//Class containing attributes of each node of tree
class Node 
{ 
    int data; 
    Node left, right; 
  
    Node(int data) 
    { 
        this.data = data; 
        left = null;
        right = null; 
    } 
} 
  
class Tree 
{ 
    Node root; 
  
    void invertTree(Node node) 
    { 
        if (node == null) 
            return; 
  
        //we call or recur for left subtrees then the right subtrees
        invertTree(node.left); 
        invertTree(node.right); 
  
        //swap the left and right child of each non-leaf node*/
        Node temp=node.left;
        node.left = node.right; 
        node.right = temp; 
  
    } 
  
  
    /* Helper function to test invertTree() by printing In-Order traversal*/
    void printInOrder(Node node) 
    { 
        if (node == null) 
            return; 
  
        printInOrder(node.left); 
        
        System.out.print(node.data + " "); 
  
        printInOrder(node.right); 
    } 
  
    /*Driver code to test for sample tree*/
    public static void main(String args[]) 
    { 
        /* creating a binary tree and entering the nodes */
        Tree tree = new Tree(); 
        tree.root = new Node(20); 
        tree.root.left = new Node(10); 
        tree.root.left.left = new Node(5); 
        tree.root.left.right = new Node(15); 
        tree.root.right = new Node(30);
        tree.root.right.left = new Node(25);
        tree.root.right.right = new Node(35);
  
        /* print inorder traversal of the input tree */
        System.out.println("Inorder traversal of Input Tree is :"); 
        tree.printInOrder(tree.root); 
        System.out.println();
        
        
        System.out.println(); 
        /* convert tree to its mirror */
        tree.invertTree(tree.root); 
  
        /* Inorder traversal of the Inverted Binary tree */
        System.out.println("Inorder traversal of Inverted Tree is : "); 
        tree.printInOrder(tree.root); 
  
    } 
}

Output:

Inorder traversal of Input Tree is :
5 10 15 20 25 30 35 

Inorder traversal of Inverted Tree is : 
35 30 25 20 15 10 5

You can see the difference in output. The In-Order traversal for the given input tree displays output in sorted order and the In-order traversal of the Inverted tree gives output in reverse sorted order.

Time Complexity: We just traverse all the nodes present in tree so the time complexity will be O(n).

Space Complexity: If we consider the system stack space for each recursive call then complexity is O(n) otherwise it is O(1).

Approach 2 (Iterative Approach)

The main idea is to do a Level Order Traversal of the tree using a Queue. We enqueue the root first into the Queue. While we traverse all the nodes at a particular level we swap the left child and right child of each node. After this, we add the left and right child child of the current node into our queue to continue the level order traversal.

Finally, we print the In-order traversal of the tree to verify the inverted tree.

Let us have a look at the implementation:

// import the Queue interface of Collections implemented using Linked List
import java.util.Queue;
import java.util.LinkedList;
//Class for each node of tree
class Node 
{ 
    int data; 
    Node left, right; 
  
    Node(int data) 
    { 
        this.data = data; 
        left = null;
        right = null; 
    } 
} 
  
class Tree 
{ 
    Node root; 
  
    void invertTreeIterative(Node root) 
    { 
        if (root == null) 
        return; 
  
        Queue<Node> queue = new LinkedList<>(); 
        //Add root first
        queue.add(root); 
      
        //We do level order traversal 
        while (queue.size() > 0) 
        { 
            // Get node of each level 
            Node curr = queue.poll();
      
            // swap left child with right child 
            Node temp = curr.left; 
            curr.left = curr.right; 
            curr.right = temp;; 
      
            // enqueue left and right child 
            if (curr.left != null) 
                queue.add(curr.left); 
            if (curr.right != null) 
                queue.add(curr.right); 
        } 
      
    } 
  
    /* Helper function to test invertTree() by printing In-Order traversal*/
    void printInOrder(Node node) 
    { 
        if (node == null) 
            return; 
  
        printInOrder(node.left); 
        
        System.out.print(node.data + " "); 
  
        printInOrder(node.right); 
    } 
  
    /*Driver code to test for sample tree*/
    public static void main(String args[]) 
    { 
        /* creating a binary tree and entering the nodes */
        Tree tree = new Tree(); 
        tree.root = new Node(20); 
        tree.root.left = new Node(10); 
        tree.root.left.left = new Node(5); 
        tree.root.left.right = new Node(15); 
        tree.root.right = new Node(30);
        tree.root.right.left = new Node(25);
        tree.root.right.right = new Node(35);
  
        /* print inorder traversal of the input tree */
        System.out.println("Inorder traversal of Input Tree is :"); 
        tree.printInOrder(tree.root); 
        System.out.println();
        
        
        System.out.println(); 
        
        /* convert tree to its mirror */
        tree.invertTreeIterative(tree.root); 
  
        /* Inorder traversal of the Inverted Binary tree */
        System.out.println("Inorder traversal of Inverted Tree is : "); 
        tree.printInOrder(tree.root); 
  
    } 
}

Output:

Inorder traversal of Input Tree is :
5 10 15 20 25 30 35 

Inorder traversal of Inverted Tree is : 
35 30 25 20 15 10 5

Time Complexity: It is same as recursive approach which require O(n) time as we traverse all nodes of tree.

Space Complexity: We use a Queue which stores all the nodes during execution so complexity is O(n).

That’s it for the article you can try and execute the above code. Feel free to ask your queries in the comment section.

The post Invert a Binary Tree – Recursive and Iterative Approach in Java appeared first on The Crazy Programmer.



from The Crazy Programmer https://ift.tt/3bjaTaI

Comments

Popular posts from this blog

Difference between Web Designer and Web Developer Neeraj Mishra The Crazy Programmer

Have you ever wondered about the distinctions between web developers’ and web designers’ duties and obligations? You’re not alone! Many people have trouble distinguishing between these two. Although they collaborate to publish new websites on the internet, web developers and web designers play very different roles. To put these job possibilities into perspective, consider the construction of a house. To create a vision for the house, including the visual components, the space planning and layout, the materials, and the overall appearance and sense of the space, you need an architect. That said, to translate an idea into a building, you need construction professionals to take those architectural drawings and put them into practice. Image Source In a similar vein, web development and design work together to create websites. Let’s examine the major responsibilities and distinctions between web developers and web designers. Let’s get going, shall we? What Does a Web Designer Do?...

A guide to data integration tools

CData Software is a leader in data access and connectivity solutions. It specializes in the development of data drivers and data access technologies for real-time access to online or on-premise applications, databases and web APIs. The company is focused on bringing data connectivity capabilities natively into tools organizations already use. It also features ETL/ELT solutions, enterprise connectors, and data visualization. Matillion ’s data transformation software empowers customers to extract data from a wide number of sources, load it into their chosen cloud data warehouse (CDW) and transform that data from its siloed source state, into analytics-ready insights – prepared for advanced analytics, machine learning, and artificial intelligence use cases. Only Matillion is purpose-built for Snowflake, Amazon Redshift, Google BigQuery, and Microsoft Azure, enabling businesses to achieve new levels of simplicity, speed, scale, and savings. Trusted by companies of all sizes to meet...

Olive and NTT DATA Join Forces to Accelerate the Global Development and Deployment of AI Solutions

U.S.A., March 14, 2021 — Olive , the automation company creating the Internet of Healthcare, today announced an alliance with NTT DATA , a global digital business and IT services leader. The collaboration will fast track the creation of new healthcare solutions to transform the health experience for humans — both in the traditional healthcare setting and at home. As a member of Olive’s Deploy, Develop and Distribute Partnership Programs , NTT DATA is leveraging Olive’s open platform to innovate, build and distribute solutions to Olive’s customers, which include some of the country’s largest health providers. Olive and NTT DATA will co-develop new Loops — applications that work on Olive’s platform to provide humans real-time intelligence — and new machine learning and robotic process automation (RPA) models. NTT DATA and Olive will devote an early focus to enabling efficiencies in supply chain and IT, with other disciplines to follow. “This is an exciting period of growth at Olive, so...