Typorithm · easy

Invert Binary Tree

invert-binary-treetreesrecursiondfsmirror
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Invert Binary Tree

0%

Trees

Recursively swap every node's left and right children to produce the mirror image of the tree.

Inverting a tree mirrors it left-to-right at every level.

Recurse into both children, then swap them — but save one side first so it is not lost.

The base case returns null for an empty subtree, and the post-order swap does the work.

01

Recurse, then swap children.

02

Save the left before overwriting it.

03

Base case: null returns null.

function invertTree(root) {
  if (root === null) {
    return null;
  }

  const left = invertTree(root.left);
  root.left = invertTree(root.right);
  root.right = left;

  return root;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Base case

An empty subtree mirrors to itself.

if (root === null) {
    return null;
  }

2. Save left first

Capture the inverted left before overwriting it.

const left = invertTree(root.left)

3. Swap subtrees

The inverted right subtree becomes the new left.

root.left = invertTree(root.right)

4. Place saved

The saved inverted left becomes the new right.

root.right = left

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Invert Binary Tree: Lesson & Practice · Typorithm | ApplyDjinn