iq.lab
Python starts when a code cell comes near or you run one
easyTrees, depth-firstRecursion target 15 min

Invert a binary tree

You get the root of a binary tree. Turn the tree into its mirror image: at every node, the left child and the right child trade places, all the way down. Change the nodes you were given and return the same root. An empty tree (None) stays empty: return None.

Trees in the examples are written in level order, the way build_tree reads them: the root, then each row from left to right, with None where a child is missing.

Example 1
Inputroot = [1, 2, 3, 4, 5, 6, 7]Output[1, 3, 2, 7, 6, 5, 4]

Every node's children swap. In a full tree like this one (every row filled), each row ends up reading backwards.

Example 2
Inputroot = [1, 2, None, 3]Output[1, None, 2, None, 3]

A chain that leans left becomes a chain that leans right.

Example 3
Inputroot = []Output[]

An empty tree is its own mirror: return None.

Constraints
  • 0 ≤ number of nodes ≤ 100

  • -100 ≤ node values ≤ 100

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.