Invert Binary Tree

25 min · invertTree()

Picture a family tree pressed against wet ink and folded down the middle. Every branch lands on the opposite side.

Given a binary tree's root, invert it by swapping the left and right children of every node, then return the root of the mirrored tree.

The transformation follows a few firm rules:

  • Node values stay unchanged.
  • Every former left subtree becomes a right subtree, and vice versa.
  • You may swap child links in place; you don't need to create new nodes.
  • An empty tree remains empty.

Constraints

  • 0 <= number of nodes <= 10_000
  • -1_000 <= node.val <= 1_000

Hints

One node at a time

At a single node, the local job is only one swap. The remaining work lives inside the two child subtrees.

Choose a traversal

Breadth-first search can swap nodes from the root downward. Depth-first search can invert both subtrees and attach them on opposite sides.

Return the same doorway

After swapping everything below root, the entry point hasn't changed. Return that root, including from recursive calls.

Follow-up

If the tree were a single branch thousands of nodes deep, how would you invert it without relying on recursion?

Visible cases

Examples

Example 1

ready
Input
root = [
  4,
  2,
  7,
  1,
  3,
  6,
  9
]
Expected
[
  4,
  7,
  2,
  9,
  6,
  3,
  1
]
Why
every left and right branch trades places

Example 2

ready
Input
root = []
Expected
[]
Why
there are no child links to swap

Example 3

ready
Input
root = [
  1
]
Expected
[
  1
]
Why
a single node is already its own mirror

Interview signal

Asked at

AmazonGoogleMeta
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite