HARD Lab · Trees · 64

226. Invert Binary Tree

Mirror a binary tree left-to-right. The whole problem reduces to one move applied everywhere: swap each node's two children, then recurse. A textbook tree-DFS in linear time.

EasyDFSBFSTypeScript

PROBLEM What we're solving

Given the root of a binary tree, return its mirror image: every node's left and right subtrees are flipped. For [4,2,7,1,3,6,9] the answer is [4,7,2,9,6,3,1] — node 4 keeps its place, but its children 2 and 7 swap, and that same flip cascades all the way down (1/3 → 3/1, 6/9 → 9/6).

KEY IDEA Mirroring = swap children, everywhere

Insight →inverting a tree is not a global rearrangement you have to plan — it's the same local operation repeated at every node: swap(node.left, node.right). Do it at the root and recurse, and the entire tree mirrors itself. The recursion is the algorithm.

RECIPE Swap then recurse

  • 0 · Base case. If the node is null, return null — an empty subtree is already its own mirror.
  • 1 · Swap. Exchange the node's left and right pointers. This is the only mutation.
  • 2 · Recurse both sides.Invert the (new) left subtree and the (new) right subtree. Order doesn't matter — each side is independent.
  • 3 · Return the node. Same object, now mirrored; bubble it back up.
Classic confusion → you do notneed to recurse before swapping, nor swap the grandchildren manually. Swap the two child pointers (which carries whole subtrees with them), then let recursion handle each side. Swapping after recursing also works — it's the same tree — but pick one and don't do both.

COST Complexity & alternatives

Rebuild a mirrored copy
O(n) time / O(n) extra
Allocates a whole second tree — unnecessary.
In-place swap + DFS
O(n) time
O(h) stack space, h = height (recursion).

DFS vs BFS

You must touch every node once, so time is O(n) either way. Recursive DFS uses O(h) call-stack space (O(log n) balanced, O(n) degenerate). An iterative BFS with a queue (or DFS with an explicit stack) is identical in spirit — pop a node, swap its children, enqueue them — and avoids deep recursion.

Pattern transfer →"do one local operation at every node, then recurse" is the backbone of Symmetric Tree (compare mirrored pairs), Maximum Depth, Same Tree, and most tree-DFS problems. Recognize the shape and the code writes itself.

RUN IT DFS down the tree, swapping every node’s two children

step 0 / 11
STARTInvert the tree by a depth-first walk: at every node, swap its left and right subtrees. Strip below is the current level-order view.
tree =40217213346596
State
4
root
children being swappedcurrent nodeafter swap / done
slowfast

TYPESCRIPT The solution, annotated

invertTree.ts
class TreeNode {
  val: number;
  left: TreeNode | null;
  right: TreeNode | null;
  constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function invertTree(root: TreeNode | null): TreeNode | null {
  if (root === null) return null;            // empty subtree: nothing to flip

  // swap the two child pointers...
  const tmp = root.left;
  root.left = root.right;
  root.right = tmp;

  invertTree(root.left);                     // ...then recurse into both sides
  invertTree(root.right);

  return root;                               // same node object, mirrored
}

Reading it block by block

Base case. A null subtree is already a mirror of itself, so return null. This also terminates the recursion at the leaves' children.
The swap. Exchange root.left and root.right via a temp (or a destructuring swap). Because these are pointers, the entire subtrees move with them — you never touch grandchildren directly.
Recurse both sides. Call invertTree on the new left and the new right. Each subtree mirrors itself independently; the order of the two calls is irrelevant.
Return root. We mutated in place, so we hand back the same node — now the root of a fully mirrored tree.
Complexity → O(n) time — every node is visited exactly once. O(h) space for the recursion stack, where h is the tree height: O(log n) for a balanced tree, O(n) worst case for a degenerate (linked-list-like) tree.

INTERVIEWFollow-ups they'll ask

  • "Do it iteratively." Use a queue (BFS) or stack (DFS): pop a node, swap its two children, push the children. Avoids recursion-depth limits on skewed trees.
  • "Why O(h) and not O(1) space?" The recursion (or your explicit stack/queue) can hold up to h frames at once on a balanced tree, n in the worst case.
  • "What if the tree is enormous and unbalanced?" Prefer the iterative version to dodge a stack overflow from O(n) recursion depth.
  • "How does this relate to checking symmetry?" Symmetric Tree compares a tree against its own mirror — the same swap intuition, but as a two-pointer comparison instead of a mutation.

MNEMONIC The one-liner

"At every node: swap the two kids, then recurse into both."

TRIGGERS When you see ___ → reach for ___

"mirror / flip / invert a tree"swap children + DFS
same op at every noderecurse(root): do-thing; recurse(L); recurse(R)
deep / skewed tree, avoid stack overflowiterative BFS queue or DFS stack
"is it symmetric?" nextcompare tree to its mirror (two pointers)

SKELETON The reusable shape

skeleton.ts
function invertTree(root: TreeNode | null): TreeNode | null {
  if (!root) return null;
  [root.left, root.right] = [root.right, root.left]; // swap
  invertTree(root.left);
  invertTree(root.right);
  return root;
}

FLASHCARDS Tap to flip

What single operation inverts a binary tree?
Swap each node's left and right children, applied at every node.
tap to flip
1 / 6
Answer to reveal explanations. No penalty for retries.Score: 0 / 7
QUESTION 01
What is the core operation performed at each node?
QUESTION 02
Time complexity of inverting the tree?
QUESTION 03
Worst-case extra space used by the recursive solution?
QUESTION 04
For root [4,2,7,1,3,6,9], what is the inverted level-order output?
QUESTION 05
Why prefer an iterative (BFS/DFS) version on a very deep, skewed tree?
QUESTION 06
Must you recurse into the subtrees before swapping?
QUESTION 07
Which related problem reuses the same "mirror" intuition?