Problem Overview
LeetCode 226 — Invert Binary Tree — gives you the root of a binary tree and asks you to invert it, producing the mirror image. Inverting a binary tree means swapping the left and right children at every node throughout the entire tree, from root to leaves. After the inversion, each node's left subtree is what was previously its right subtree, and vice versa.
This problem is labeled Easy and is one of the most recognized problems in competitive programming lore. It can be solved recursively in fewer than 4 lines of code, yet it tests understanding of tree traversal, recursion, and the relationship between different algorithmic approaches. The iterative solutions using BFS and DFS add depth to an otherwise brief problem.
The constraints are straightforward: the tree can have between 0 and 100 nodes, and node values are integers between -100 and 100. An empty tree (null root) should simply return null — this is the natural recursive base case and requires no special handling.
- Input: root of a binary tree
- Output: root of the inverted (mirrored) tree
- Swap left and right children at every node
- Empty tree (null) returns null
- Node values range from -100 to 100
- Tree size up to 100 nodes
The Famous Story
In 2015, Max Howell — the creator of Homebrew, the most widely used macOS package manager — tweeted that Google had rejected him because he could not invert a binary tree on a whiteboard. The tweet went viral and ignited a fierce debate about whether whiteboard coding interviews accurately assess engineering ability. Howell's software was installed on millions of machines, yet a single algorithmic puzzle had disqualified him.
The meme has endured for over a decade. It surfaces every time someone questions the value of algorithm interviews, and the phrase "invert a binary tree" has become shorthand for the perceived disconnect between real-world engineering and interview performance. Whether you agree with the critique or not, the problem itself is genuinely useful for teaching recursive tree thinking.
The irony is that LeetCode 226 is actually an excellent teaching problem. It has a clean recursive solution, multiple valid iterative approaches, and illustrates a key insight: the order in which you process nodes does not matter when each operation is local and independent. It is the kind of problem that reveals how recursion mirrors the structure of the data it operates on.
The Real Lesson
Despite the meme, this problem teaches the fundamental recursive tree pattern: process node, recurse on children. The swap at each node is independent of all other swaps, which is why both preorder and postorder recursion produce the same correct result — and why BFS and DFS are equally valid iterative approaches.
Recursive Approach
The recursive solution is the most natural fit for this problem. A binary tree is a recursive structure — each node is the root of its own subtree — so inverting it recursively mirrors the structure perfectly. The logic is: if the current node is null, return null (base case). Otherwise, swap its left and right children, then recursively invert both subtrees.
In Python, this is literally 4 lines: def invertTree(root): if not root: return None; root.left, root.right = root.right, root.left; invertTree(root.left); invertTree(root.right); return root. The swap happens before recursing, making this a preorder traversal — but as noted, postorder (swap after recursing) also works correctly.
The time complexity is O(n) because every node is visited exactly once. The space complexity is O(h) where h is the height of the tree, due to the recursion call stack. In the worst case (a completely unbalanced tree), h equals n, giving O(n) space. For a balanced tree, h is O(log n).
- 1Base case: if node is null, return null
- 2Swap: node.left, node.right = node.right, node.left
- 3Recurse: invertTree(node.left)
- 4Recurse: invertTree(node.right)
- 5Return root
Iterative BFS
The iterative BFS approach uses a queue to process nodes level by level. Start by enqueuing the root. At each step, dequeue a node, swap its left and right children, then enqueue both children (if non-null). Continue until the queue is empty. The tree is fully inverted when every node has been processed.
In Python, use collections.deque for efficient O(1) popleft operations: from collections import deque; q = deque([root]); while q: node = q.popleft(); node.left, node.right = node.right, node.left; if node.left: q.append(node.left); if node.right: q.append(node.right); return root. This processes all nodes at depth 0, then depth 1, then depth 2, and so on.
BFS is useful when you want to process the tree level by level, or when the tree is very deep and you want to avoid Python's recursion limit. The time complexity remains O(n) and the space complexity is O(w), where w is the maximum width of the tree — the maximum number of nodes at any single level.
Order Does Not Matter
BFS and DFS both work correctly because the order of inversion does not matter: swapping children at any node is independent of swaps at other nodes. Whether you process root-to-leaf (preorder/BFS) or leaf-to-root (postorder), every node gets swapped exactly once and the final tree is identical.
Iterative DFS with Stack
The iterative DFS approach is structurally identical to BFS but replaces the queue with a stack. Push the root onto the stack. At each step, pop a node, swap its children, then push both non-null children onto the stack. The stack causes depth-first processing — the most recently pushed child is processed next, diving deep before backtracking.
In Python: stack = [root]; while stack: node = stack.pop(); node.left, node.right = node.right, node.left; if node.left: stack.append(node.left); if node.right: stack.append(node.right); return root. The only difference from BFS is pop() instead of popleft() and a list instead of a deque — the swap logic is identical.
Iterative DFS mimics the call stack of the recursive solution without the overhead of actual function calls. For very deep trees it avoids hitting Python's default recursion limit (usually 1000 frames), making it the safest iterative option for production use. Time complexity is O(n) and space complexity is O(h) for the stack depth.
- 1Initialize stack with [root]
- 2While stack is not empty: node = stack.pop()
- 3Swap: node.left, node.right = node.right, node.left
- 4If node.left: stack.append(node.left)
- 5If node.right: stack.append(node.right)
- 6Return root after stack is exhausted
Code Walkthrough Python and Java
Python recursive (4 lines): def invertTree(root): if not root: return None; root.left, root.right = root.right, root.left; invertTree(root.left); invertTree(root.right); return root. Python BFS: from collections import deque; q = deque([root]); while q: n = q.popleft(); n.left, n.right = n.right, n.left; q.extend(c for c in [n.left, n.right] if c); return root. Both run in O(n) time and O(n) space.
Java recursive: public TreeNode invertTree(TreeNode root) { if (root == null) return null; TreeNode tmp = root.left; root.left = root.right; root.right = tmp; invertTree(root.left); invertTree(root.right); return root; }. Java iterative BFS: Queue<TreeNode> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { TreeNode n = q.poll(); TreeNode tmp = n.left; n.left = n.right; n.right = tmp; if (n.left != null) q.add(n.left); if (n.right != null) q.add(n.right); } return root;.
All three versions — recursive, BFS, DFS stack — run in O(n) time and O(n) space. The recursive version has the smallest code footprint and is preferred in interviews. The iterative versions are preferred in production systems with deep trees. Java uses a temporary variable for swapping since it lacks Python's tuple swap syntax.
Swap Before Recursing
In the recursive solution, swap children BEFORE recursing, not after. While postorder (swap after) also produces the correct result for this specific problem, swapping before (preorder) is the conventional approach and avoids confusion. Swapping after means you recurse into the original subtrees and swap them after they are already fully inverted — it works but is harder to reason about.