Invert Binary Tree, visualized step by step

Easy One of the Blind 75 interview problems (LeetCode 226). Technique: tree recursion. Solution in Python, explained at every step.

The problem

You get the root of a binary tree. Invert it: for every node, its left subtree becomes its right one and the other way round, so the whole tree turns into its mirror image. Return the root.

Example: a root 8 with 3 on the left (children 1 and 6) and 12 on the right (children 10 and 15) becomes 8 with 12 on the left (children 15 and 10) and 3 on the right (children 6 and 1).

Input: the root 8 with children 3 and 12; 3 has the children 1 and 6, and 12 has 10 and 15. Answer: the root 8 with children 12 and 3; 12 has the children 15 and 10, and 3 has 6 and 1.
Every node's two children trade places, not only the root's.

Try it yourself first: LeetCode 226 ↗. Then step through the solution below.

Brute force

Build a mirrored copy: create a new node for every node, with the copy of its right subtree on the left and the copy of its left subtree on the right. That is O(n) time too, but it allocates n new nodes, O(n) extra space, when the original nodes can simply be relinked.

The key insight

The mirror of a tree is its root with the mirror of the right subtree on the left and the mirror of the left subtree on the right. So a node has only one job: swap its two children. Then the same job is left for each child.

That is the same problem on smaller trees, which is what recursion is for: swap at the root, call the function on both children, and stop at an empty child.

Note

A common slip is two plain lines: root.left = invert(root.right), then root.right = invert(root.left). The second line reads the new left child, so the old left subtree is lost. Save one child first, or swap both in one statement as here. The swap can come before the two calls or after them: both give the mirror. Between them it cannot: after the left subtree is inverted and the children are swapped, the right child is that same subtree, so a call on it inverts it back.

Step by step

The player runs the code on the example. Press → for each step: the lines it runs light up in the code.

On a phone, Full screen keeps the picture and the code on one screen.

Invert Binary Tree, step by step

Python

class TreeNode:    def __init__(self, val, left=None, right=None):        self.val, self.left, self.right = val, left, right def invert(root):    if root is None:        return None    root.left, root.right = root.right, root.left    invert(root.left)    invert(root.right)    return root
All steps as text
  1. The tree has 8 at its root, 3 on the left, 12 on the right. Inverting mirrors it: each left child becomes a right one.
  2. The function is called on the root, 8. In the mirror image, its children 3 and 12 must trade sides.
  3. At the root, 8, swap the two subtrees: 12 and its children move to the left, 3 and its children to the right.
  4. The call on 8 calls the function on its new left child, 12, and waits until that call returns.
  5. The call on 12 swaps its children: 15 goes left and 10 right.
  6. The call on 12 calls the function on its left child, 15, a leaf. Its calls on its empty children stop at once.
  7. The call on 12 now calls the function on its right child, 10. A leaf too: its calls on empty children stop at once.
  8. The calls on 15 and 10 have returned, so the call on 12 returns too.
  9. The call on 8 now calls the function on its right child, 3.
  10. The call on 3 swaps its children: 6 goes left and 1 right.
  11. The call on 3 calls the function on its left child, 6, a leaf. Its calls on its empty children stop at once.
  12. The call on 3 now calls the function on its right child, 1. A leaf too: its calls on empty children stop at once.
  13. The calls on 6 and 1 have returned, so the call on 3 returns too.
  14. Every call has returned but the first one, which returns 8, the root of the mirrored tree.
  15. Each node was visited once: O(n) time, with as many calls waiting as the tree is deep: O(h) space.
Invert Binary Tree, step by step. Last step: Each node was visited once: O(n) time, with as many calls waiting as the tree is deep: O(h) space.

Complexity

ApproachTimeSpace
Brute force: build a mirrored copyO(n)O(n)
A queue instead of recursionO(n)O(w)
Swap the children, recursively this pageO(n)O(h)

h is the height of the tree, and w the number of nodes on its widest level.

  • Time: O(n). Each node is visited once and its swap is O(1).
  • Space: O(h). The calls wait on the call stack, one per level of the tree: O(log n) for a balanced tree, O(n) for a tree that is one long chain.

Note

Python allows 1,000 nested calls by default, so a chain of about a thousand nodes raises RecursionError. Java and C++ have no fixed count: the limit is the thread's stack size, which usually allows many thousands of calls.

Edge cases

  • An empty tree: the first check returns None at once.
  • A single node: its two empty children are swapped, which changes nothing, and the same node comes back.
  • A chain of left children, like 3 → 2 → 1 down the left side: it becomes the same chain down the right side. The recursion goes as deep as the chain is long.

Try it: put Invert Binary Tree together step by step

The blocks below are steps of Invert Binary Tree in words, and one of them does not belong. A block that works on a subtree “the same way” runs your lines again, from line 1, on that subtree. Put the right ones in order and check: your algorithm runs on the example and on a chain, 3 with a left child 2 with a left child 1, so a mistake shows in its answer. Once it is right, the code appears beside your blocks.

Put Invert Binary Tree together

Click the blocks in the order they run, or drag them into the lines.Tap the blocks in the order they run. One of them doesn't belong.

Your algorithm

To invert the tree under root:

Blocks

Interview follow-up

Can you do it without recursion? Yes, with a queue: take a node out, swap its children, and put the children that are not empty in. It is the same O(n) time, the queue holds the end of one level and the start of the next, and a very deep tree cannot hit the recursion limit.

The data structure behind it

  • Binary search tree: nodes with a left and a right child, step by step.
  • Preorder traversal: the order these calls visit the nodes: a node, then its left subtree, then its right one.