Invert Binary Tree

Try to solve the Invert Binary Tree problem.

Statement#

Given the root node of a binary tree, transform the tree by swapping each node’s left and right subtrees, thus creating a mirror image of the original tree. Return the root of the transformed tree.

Constraints:

  • 00\leq Number of nodes in the tree 100\leq 100
  • 1000-1000 \leq Node.value 1000\leq 1000

Examples#

Created with Fabric.js 3.6.6 1 2 3 1 3 2 Input: Original tree level order Output: Mirrored tree level order 1 2 3 1 3 2 Sample example 1

1 of 3

Created with Fabric.js 3.6.6 10 5 20 2 7 10 20 5 7 2 Input: Original tree level order Output: Mirrored tree level order Sample example 2 10 5 20 2 7 10 20 5 null null 7 2

2 of 3

Created with Fabric.js 3.6.6 Input: Original tree level order 100 50 200 25 75 350 100 200 50 350 75 25 Output: Mirrored tree level order 100 50 200 25 75 null 350 100 200 50 350 null 75 25 Sample example 3

3 of 3

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Invert Binary Tree

1

What is the correct mirrored tree for the given tree?

  5 / \6   7   / \  8   9
A)
  5 / \6   7   / \  8   9
B)
    5   / \  7   6 / \  9   8
C)
  5 / \6   7   / \  9   8
D)
  5 / \7   6   / \  9   8
Question 1 of 20 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Drag and drop the cards to rearrange them in the correct sequence.

Perform post order traversal on the left child of the root node.

Perform post order traversal on the right child of the root node

Swap the left and right children of the root node.


Try it yourself#

Implement your solution in main.py in the following coding playground.

Python
usercode > main.py
Input #1
%0 node_1 100 node_2 50 node_1->node_2 node_3 200 node_1->node_3 node_4 25 node_2->node_4 node_5 75 node_2->node_5 node_6 125 node_3->node_6 node_7 350 node_3->node_7
Visualization for Input #1
Invert Binary Tree

Solution: Balanced Binary Tree

Solution: Invert Binary Tree