Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.

Try one problem
0
Problem

Invert Binary Tree

LeetCode #226Easy
Pre-order DFS, swap every node's children

Given the root of a binary tree, invert it (mirror it left-to-right) and return the root. The interview classic that, per legend, once tripped up a well-known whiteboard candidate.

Asked atGoogleAmazonApple
step 1 / 29
binary tree
9
7
6
4
3
2
1
call stack ↓
(returned)
Recursive DFS (swap children)
1invert(node):
2 if node is null: return // base case
3 swap node.left, node.right // pre-order: act, then descend
4 invert(node.left)
5 invert(node.right)
6 return // subtree mirrored
7// answer = inverted root
state
  • goalmirror the tree
  • orderpre-order swap

line 1Invert (mirror) the tree: every node trades its left and right child. Folklore says a famous engineer once flunked an interview for failing to invert a tree on a whiteboard — but it is just one idea applied everywhere. We use pre-order DFS: at each node SWAP its two children first, then recurse into the (now-swapped) children. Because swapping is symmetric, a child finds the same job waiting no matter which side it landed on.