PROBLEM 22 OF 75

Invert Binary Tree

Swap the left and right child of every tree node.

PATTERNTrees & recursive traversalDefine the meaning of one recursive return value.
SPOT THE SIGNAL

Why does this pattern fit?

FRAME · 1 OF 4

Restate the exact job

Swap the left and right child of every tree node.

WHY THIS FITS

Each node’s answer depends only on inverted child subtrees.

COMPLEXITY

O(n) time · O(h) call stack

COMMON FAILURE

Swapping after overwriting one child can lose a subtree.

THE REASONING, IN ONE PLACE

How to solve Invert Binary Tree

The goal is to solve this problem from the pattern, not to memorize a finished answer. Use this as a check after your own attempt.

What the question asks

Swap the left and right child of every tree node.

Why Trees & recursive traversal fits

Each node’s answer depends only on inverted child subtrees.

State to maintain

A node and the inverted results of its children.

Transition

Recursively invert both children, swap them, and return the node.

Time and space

O(n) time · O(h) call stack

Counterexample to the tempting mistake

Swapping after overwriting one child can lose a subtree.

Prove it again tomorrow

Close this page. Rebuild the state and transition from memory, write a test that exposes the mistake above, then solve a fresh input without looking back. A same-day reread is practice, not proof of retention.

Open blank recall ↗