Search⌘ K
AI Features

Invert Binary Tree

Explore how to invert a binary tree by swapping each node’s left and right children using depth-first search. This lesson helps you understand the problem constraints, develop a clear algorithmic approach, and implement the solution in JavaScript, strengthening your coding interview skills.

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

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

1 / 2

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.

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

1
2
3

Try it yourself

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

JavaScript
usercode > main.js
// Definition of a binary tree node
// class TreeNode {
// constructor(data) {
// this.data = data;
// this.left = null;
// this.right = null;
// }
// }
import {TreeNode} from './ds_v1/BinaryTree.js';
function mirrorBinaryTree(root) {
// Replace this placeholder return statement with your code
return root;
}
export{ mirrorBinaryTree };
Invert Binary Tree