Invert Binary Tree easy
Description
Given the root of a binary tree, invert it — swap every node’s left and right child throughout the tree — and return the root.
Examples
> Case 1:
Input: 4 Output: 4
/ \ / \
2 7 7 2
/ \ / \ / \ / \
1 3 6 9 9 6 3 1
> Case 2:
Input: [2, 1, 3]
Output: [2, 3, 1]
> Case 3:
Input: []
Output: []The famous “Homebrew interview”
This problem is famously the one Max Howell (author of Homebrew, a Mac package manager that powers most of Apple’s development tools) was reportedly rejected from Google for not being able to whiteboard. The internet still memes about it. Be ready.
The solution is three lines.
The recursive answer
Three-question recipe:
- Base case: inverting an empty tree gives the empty tree.
- Recursive case: invert the left and right subtrees, then swap them.
- Combine: assign the swapped pointers back to the node.
The Python one-liner root.left, root.right = invert_tree(root.right), invert_tree(root.left) is elegant — Python’s tuple unpacking evaluates both calls first, then assigns. In C++ and Java you need a temp because the recursive calls evaluate one at a time and would clobber each other if assigned directly.
Iterative variant (with a queue or stack)
Same idea, just iterating through nodes and swapping children:
from collections import deque
def invert_tree(root):
if root is None: return None
queue = deque([root])
while queue:
node = queue.popleft()
node.left, node.right = node.right, node.left
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return rootOrder of visits doesn’t matter — every node gets swapped exactly once regardless.
Why it works
Each node swaps its two child pointers. Before the swap, the subtrees are correctly inverted (by the recursive precondition). After the swap, the left child is what was the right inverted subtree, and vice versa. The result is the full inversion.
Analysis
- Time: O(n) — every node touched once.
- Space: O(h) for recursion stack; O(w) for the iterative BFS queue.