226. Invert Binary Tree
easyMirror a binary tree by swapping every node's left and right subtrees. Famous as the question that prompted a viral 'we want our engineers to know this' tweet — a clean two-line recursive solve.
By Alex Chen, Founder, InterviewChamp.AI · Last verified
Problem
Given the root of a binary tree, invert the tree, and return its root.
Constraints
The number of nodes in the tree is in the range [0, 100].-100 <= Node.val <= 100
Examples
Example 1
root = [4,2,7,1,3,6,9][4,7,2,9,6,3,1]Example 2
root = [2,1,3][2,3,1]Example 3
root = [][]Solve it now
Free. No sign-up. Python and JavaScript run instantly in your browser.
Hints
Progressive — try the first before opening the next.
Hint 1
Recurse: invert both subtrees, then swap them.
Hint 2
Base case: null returns null.
Hint 3
Iterative BFS or DFS works — swap children at every node visited.
Solution approach
Reveal approach
Recursive swap. If node is null, return null. Otherwise compute leftInverted = invert(node.left) and rightInverted = invert(node.right) — then assign node.left = rightInverted and node.right = leftInverted, and return node. Equivalent iterative version: BFS with a queue, popping each node and swapping its children before enqueueing them. O(n) time, O(h) space.
Complexity
- Time
- O(n)
- Space
- O(h)
Related patterns
- dfs
- recursion
Related problems
- 101. Symmetric Tree
- 156. Binary Tree Upside Down
Asked at
Companies reported asking this problem (sourced from public Glassdoor, Blind, and Levels.fyi interview posts).
- Amazon
- Apple
Practice these live with InterviewChamp.AI
Drill Invert Binary Tree and Trees problems under real interview conditions with instant feedback on your reasoning, complexity claims, and code.
Practice these live with InterviewChamp.AI →