VOOZH about

URL: https://www.geeksforgeeks.org/dsa/create-a-mirror-tree-from-the-given-binary-tree/

⇱ Create a mirror tree from the given binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Create a mirror tree from the given binary tree

Last Updated : 26 Mar, 2023

Given a binary tree, the task is to create a new binary tree which is a mirror image of the given binary tree.

Examples: 

Input:
 5
 / \
 3 6
 / \
 2 4
Output:
Inorder of original tree: 2 3 4 5 6 
Inorder of mirror tree: 6 5 4 3 2
Mirror tree will be:
 5
 / \
6 3
 / \
 4 2

Input:
 2
 / \
 1 8
 / \
 12 9
Output:
Inorder of original tree: 12 1 2 8 9 
Inorder of mirror tree: 9 8 2 1 12

Approach: Write a recursive function that will take two nodes as the argument, one of the original tree and the other of the newly created tree. Now, for every passed node of the original tree, create a corresponding node in the mirror tree and then recursively call the same method for the child nodes but passing the left child of the original tree node with the right child of the mirror tree node and the right child of the original tree node with the left child of the mirror tree node.

Below is the implementation of the above approach: 


Output
Inorder of original tree: 2 3 4 5 6 
Inorder of mirror tree: 6 5 4 3 2 

Time Complexity: O(n), where n is the number of nodes in the tree. This is because we need to visit each node in the tree exactly once to swap its left and right child nodes.
Auxiliary Space: O(h), where h is the height of the binary tree. This is because the maximum amount of space used by the algorithm at any given time is the size of the call stack, which is at most equal to the height of the binary tree. This is because each recursive call to mirror adds a new frame to the call stack, and the stack grows to a maximum depth of the height of the tree. Therefore, the space used by the algorithm is proportional to the height of the tree.

Approach 2:
 In order to change the original tree in its mirror tree, then we simply swap the left and right link of each node. If the node is leaf node then do nothing.


Output
Inorder of original tree: 2 3 4 5 6 
Inorder of Mirror tree: 6 5 4 3 2 

Time complexity: O(N) where N is the number of nodes in given binary tree.
Auxiliary Space: O(h) where h is the height of the tree. due to recursion call stack.

Comment
Article Tags:
Article Tags: