Invert Binary Tree
Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.
Given the root of a binary tree, invert it (mirror it left to right) and return its root.
Understand the problem
- A binary tree is made of nodes. Each node has a value and up to two children: a left child and a right child. The top node is the root. (New to trees? Read the beginner guide linked at the top.)
- Inverting means swapping every node's left and right children, at every level, as if you held the tree up to a mirror.
Example 1
Input: root = [4, 2, 7, 1, 3, 6, 9]
Output: [4, 7, 2, 9, 6, 3, 1]
4 4
/ \ / \
2 7 → 7 2
/ \ / \ / \ / \
1 3 6 9 9 6 3 1Not only did 2 and 7 swap: inside each of them, the children swapped too.
Example 2
Input: root = [2, 1, 3]
Output: [2, 3, 1]Example 3
Input: root = []
Output: []An empty tree stays empty.
How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child. [1, 2, 3, null, 4] is a root 1 with children 2 and 3, where 2 has only a right child 4. [] is an empty tree.
Constraints
0 <= number of nodes <= 100
Hints
Stuck? Open one hint at a time. Each one gives away a little more than the last.
The idea in one sentence
At every node, swap its left and right children, and let recursion do the same for every subtree below.
Thinking recursively
This is a gentle introduction to the way almost every tree problem is solved. A tree is a node plus two smaller trees (its left and right subtrees). So instead of thinking about the whole tree, ask:
What do I need to do at one node, assuming a recursive call already handles each subtree?
Here the answer is short:
- Invert the left subtree (recursive call).
- Invert the right subtree (recursive call).
- Swap them: the inverted right becomes the new left, and the inverted left becomes the new right.
And the base case, where the recursion stops: an empty tree (null) is already inverted.
Step by step
4
/ \
2 7| Call | What happens | Returns |
|---|---|---|
invert(4) | needs invert(2) and invert(7) first | (waits) |
→ invert(2) | its children are null → swap two nulls | 2 |
→ invert(7) | its children are null → swap two nulls | 7 |
back in invert(4) | 4.left = 7 (inverted right), 4.right = 2 (inverted left) | 4 ([4, 7, 2]) |
With deeper trees, each call does the same thing one level down, and the swaps happen on the way back up.
The code
The reference solution is below, with comments on every important line.
How fast is it?
- Time: O(n). Every node is visited exactly once.
- Memory: O(h), where
his the tree's height. Each recursive call waits on the call stack until its children are done, and at mosthcalls are waiting at once. That's O(log n) for a balanced tree, but O(n) for a tree that's just one long chain.
Common mistakes
- Overwriting before saving. If you write
root.left = invert(root.right)first, the oldroot.leftis gone before you can invert it. Save it in a variable first (or swap both at once, as in the Python version). - Only swapping the root's children. The whole tree must be mirrored, at every level. That's why the recursive calls are needed.
- Forgetting the base case. Without
if (!root) return null, the code tries to read.leftofnulland crashes.
Going deeper
- You can also invert with BFS: visit nodes level by level using a queue and swap the children of each one. Same result, and no deep recursion on a very lopsided tree.
- This problem became famous when a well-known developer joked about failing it in an interview. Short problems still deserve a clean, confident answer.
Reference solution
/**
* @param {TreeNode | null} root
* @return {TreeNode | null}
*/
export default function invertTree(root) {
// Base case: an empty tree is already inverted.
if (!root) return null
// Save the inverted left subtree BEFORE we overwrite root.left.
const left = invertTree(root.left)
// Swap: the inverted right subtree goes on the left...
root.left = invertTree(root.right)
// ...and the inverted left subtree goes on the right.
root.right = left
return root
}export default function invertTree(root: TreeNode | null): TreeNode | null {
// Base case: an empty tree is already inverted.
if (!root) return null
// Save the inverted left subtree BEFORE we overwrite root.left.
const left = invertTree(root.left)
// Swap: the inverted right subtree goes on the left...
root.left = invertTree(root.right)
// ...and the inverted left subtree goes on the right.
root.right = left
return root
}def invert_tree(root: TreeNode | None) -> TreeNode | None:
# Base case: an empty tree is already inverted.
if root is None:
return None
# Invert both subtrees and swap them. Python evaluates the whole right side
# before assigning, so nothing is overwritten too early.
root.left, root.right = invert_tree(root.right), invert_tree(root.left)
return root