Invert Binary Tree (LeetCode 226): Solution and Explanation

Easy
Tree
Depth First Search
Breadth First Search
Binary Tree

Given the root of a binary tree, turn it into its mirror image by swapping the left and right children of every node, and return the root.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Picture the tree reflected in a vertical mirror placed next to it. The root stays where it is, everything that was on its left ends up on its right, and the same is true inside each subtree, all the way down. So mirroring the whole tree means two things at every node: swap its two children, and make sure each of those children is itself mirrored.

That description is already recursive. To invert a tree rooted at root, swap root.left and root.right, then invert the left subtree and invert the right subtree. The base case is an empty subtree, which is its own mirror, so you return None and stop. There is no need to build new nodes; the existing nodes are rewired in place.

The order of the swap relative to the recursive calls is flexible. The reference code swaps first and then recurses into the new left and new right children, which is a pre-order traversal. Recursing first and swapping afterward (post-order) works just as well. What does not work is an in-order version that recurses left, swaps, then recurses left again without adjusting, because after the swap the subtree you already inverted has moved to the right, and you end up flipping one side twice and the other side not at all.

A quick sanity check for any version you write: inverting a tree twice should give back the original tree. Running your function twice on a small example and comparing with the input is an easy way to catch a version that flips one subtree twice and leaves another untouched.

Approach: Recursive pre-order swap

  1. If root is None, return None.
  2. Swap the children in one line: root.left, root.right = root.right, root.left.
  3. Recursively invert the new left subtree with self.invertTree(root.left).
  4. Recursively invert the new right subtree with self.invertTree(root.right).
  5. Return root, which is now the root of the mirrored tree.

Step-by-step example

root = [4, 2, 7, 1, 3, 6, 9]
  1. At node 4, swap its children so the left child becomes 7 and the right child becomes 2.
  2. Recurse into 7 (now on the left). Swap its children 6 and 9, so 7 has left 9 and right 6. Both are leaves, whose calls swap two Nones and return.
  3. Recurse into 2 (now on the right). Swap its children 1 and 3, so 2 has left 3 and right 1.
  4. Reading the tree level by level now gives [4, 7, 2, 9, 6, 3, 1], which is the mirrored tree.

Code: Python, Java, C++

1class Solution:
2    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
3        if not root:
4            return None
5        
6        root.left, root.right = root.right, root.left
7        
8        self.invertTree(root.left)
9        self.invertTree(root.right)
10        
11        return root

Time and space complexity

Time

O(n)

Each node is visited once and its children are swapped in constant time.

Space

O(h)

The recursion depth equals the height h of the tree: O(log n) when balanced and O(n) for a skewed chain.

Other approaches

Iterative BFS with a queue (time O(n), space O(w))

Pop a node from a queue, swap its children, and enqueue any non-null children. It avoids recursion limits and visits nodes level by level, using memory proportional to the widest level.

Iterative DFS with a stack (time O(n), space O(h))

Same as BFS but with a stack, so nodes are processed depth first. It is a direct translation of the recursive solution with an explicit stack.

Common mistakes

  • Swapping with two separate assignments such as root.left = root.right followed by root.right = root.left. The original left child is lost; use a tuple swap or a temporary variable.
  • Doing an in-order traversal that recurses left, swaps, then recurses right. After the swap, the right subtree is the one you already inverted, so it gets flipped back.
  • Forgetting to return root at the end. The function must hand back the tree, not just modify it, for callers that use the return value.
  • Building a brand new mirrored tree when in-place modification is fine. It works but doubles the memory for no benefit.

Frequently asked questions

What does it mean to invert a binary tree?

It means producing the tree's mirror image: at every node, the left and right children trade places. Leaves stay leaves, and the root stays the root.

Can you invert a binary tree iteratively?

Yes. Use a queue or stack, and for each node you take out, swap its children and add the non-null children back in. The complexity is the same as the recursive version.

Does the order of swapping and recursion matter?

Pre-order and post-order both work. A naive in-order version breaks, because the swap moves the already processed subtree to the side you visit next.

What is the time complexity of inverting a binary tree?

O(n), since every node is visited once. Space is O(h) for recursion, where h is the height of the tree.