Algorithms · Trees & recursion

Invert a Binary Tree

Mirror a tree: every left becomes right.

The problem

Mirror the tree: every node’s left and right children swap places, all the way down. Return the top of the flipped tree.

check([4, 2, 7, 1, 3, 6, 9])[4, 7, 2, 9, 6, 3, 1]
check([2, 1, 3])[2, 3, 1]
Trees & recursion. Solve the small one first. Russian dolls: open one, and inside is a smaller doll of the same kind.

Now ask: what if there were a billion?

Trees hold huge things: a browser page can have tens of thousands of nodes, and a file system millions. Walking them once (O(n)) is the most any of these jobs should cost.

Aim for O(n)🧩 classic

Think it through

What is “flip this tree” made of?

  • Flip the left part, flip the right part, swap them
  • Swap the two children at the top
Show the answer

Flip the left part, flip the right part, swap them. Swapping only the top leaves everything below unflipped. Flip each child (the same job, smaller), then swap.

What does flipping an empty tree give?

  • An error
  • An empty tree
Show the answer

An empty tree. The base case: nothing to flip. Get that right and the recursion handles every shape of tree.

Stuck? 3 nudges, smallest first
  1. Flipping a tree means flipping its left part, flipping its right part, and swapping them.
  2. That’s recursion: invert the children first, then swap.
  3. root.left, root.right = invert(root.right), invert(root.left), then return root.

The fast way

Try it yourself before you open this.

Show the fast version
def invert(root):take the top of a tree
if root is None:nothing here?
return Nonenothing to flip
root.left, root.right = invert(root.right), invert(root.left)flip both sides, then swap them
return roothand back the top

Solve it yourself.

It runs right in the page: the tests, the gremlins that try to break it, and a race up to a billion. Free, nothing to install.

More with trees & recursion