Convert a Binary Tree to its Mirror Tree

Given a binary tree, convert this binary tree into its mirror tree. A binary tree is a tree in which each parent node has at most two children. The mirror of a binary tree T is another binary tree M(T) with left and right children of all non-leaf nodes interchanged.

Input:

The first line of input contains an integer ‘T’ denoting the number of test cases. 
The input for each test case contains the elements of the tree in level order form separated by a single space. If a node does not have a left or right child, use -1 in its place.

Output:

For every test case, output the inorder traversal of the mirror tree on a separate line. The elements of the mirror tree should be represented in level order form separated by a single space, with -1 in place of NULL left or right child.

Example:

Input:
1 
1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Explanation:
Level 1 : 
The root node of the tree is 1

Level 2 :
Left child of 1 = 2
Right child of 1 = 3

Level 3 :
Left child of 2 = 4
Right child of 2 = null (-1)
Left child of 3 = 5
Right child of 3 = 6

Level 4 :
Left child of 4 = null (-1)
Right child of 4 = 7
Left child of 5 = null (-1)
Right child of 5 = null (-1)
Left child of 6 = null (-1)
Right child of 6 = null (-1)

Level 5 :
Left child of 7 = null (-1)
Right child of 7 = null (-1)

The input format presented here indicates how to represent the tree structure using level order traversal, including null nodes as -1.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 3000
  • -109 <= DATA <= 109
  • Time Limit: 1 sec
Note:
You are required to make in-place changes to modify the nodes of the given binary tree to achieve the desired mirror tree. You do not need to print anything; it has already been handled. Just implement the given function.
Be the first one to answer
Add answer anonymously...
24/7 Customer Software Developer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+

Reviews

4 L+

Interviews

4 Cr+

Salaries

1 Cr+

Users/Month

Contribute to help millions

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter