Invert Binary Tree
Problem
You are given the root of a binary tree. Produce its mirror image: for every node in the tree, the left and right subtrees trade places. Do the transformation in place, reusing the existing nodes, and return the root.
- The tree has at most 2,000 nodes.
- Node values are small integers in the range -500 to 500; duplicates are allowed.
- The input may be empty (
rootisNone), in which case returnNone.
Examples
root = [5, 3, 8, 1, 4, None, 9]→[5, 8, 3, 9, None, 4, 1]. The root keeps its value; its two subtrees swap, and inside each of them the children swap again, so 8's lone right child 9 becomes a lone left child.root = [7, 2, 11]→[7, 11, 2]. Only one swap is needed at the root.root = []→[]. Nothing to invert.
(Lists are level-order with None marking a missing child, the usual convention in this guide.)
Hints
- Look at the root by itself. What has to happen to its two child pointers, regardless of what is underneath them?
- Suppose both subtrees were already mirrored. What work remains at the current node?
- A depth-first traversal that swaps
leftandrightat every node is the whole algorithm; recursion handles the subtrees.
Last reviewed 8 September 2026
Approach · Solution (Python) · Complexity · Follow-ups · Company variations · Tests
The rest of this question — the worked approach, the Python solution with passing tests, complexity, follow-ups and how each company frames it — is part of the guides.
Get the full guide
Pick the company you're interviewing with. Each guide has every question tiered for that loop — one-time purchase, lifetime access.
Also in: Apple, Google, Meta, Microsoft, Netflix
Interviewing at more than one? All 6 guides for $499 · save $395
Not ready to buy? Get the free starter pack — 13 questions with full solutions.