Convert a Binary Tree to it’s Mirror

Java Implementation of coverting a binary tree to it’s Mirror.

class Solution
{
    static class TreeNode{
        int data;
        TreeNode left,right;
        TreeNode(int data)
        {
            this.data=data;
        }
    }
    static void inorder(TreeNode root)
    {
        if(root==null)
            return;
        inorder(root.left);
        System.out.print(root.data+" ");
        inorder(root.right);
    }
    static void mirror(TreeNode root)
    {
        if(root==null)
        return;
        
        mirror(root.left);
        mirror(root.right);
        
        TreeNode temp=root.left;
        root.left=root.right;
        root.right=temp;
    }
     public static void main(String[] args)
    {
        TreeNode root=new TreeNode(1);
        root.left=new TreeNode(2);
        root.right=new TreeNode(3);
        root.left.left=new TreeNode(4);
        root.left.right=new TreeNode(7);
        
        inorder(root);
        System.out.println();
        
        mirror(root);
        
        inorder(root);
         
    }
    }

Output: Inorder Traversal of Binary Tree- 4 2 7 1 3

Inorder Traversal of Mirror Tree- 3 1 7 2 4

Time Complexity- O(n)

Space Complexity- O(n)

Leave a comment

Your email address will not be published. Required fields are marked *

Pin It on Pinterest