CodingNodes / Trees / Invert Binary Tree System design Space play · ←→ step · R restart

Problem

Given the root of a binary tree, produce its mirror image: at every node, the left and right subtrees trade places.

Return the root of the mirrored tree. The tree is given in level order, with null for a missing child.

Constraints

  • 0 ≤ number of nodes ≤ 100
  • -100 ≤ Node.val ≤ 100

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(h)

Time: Every node is visited once, and the swap at each node takes constant time.

Space: The recursion goes as deep as the tree is tall, h. That is log n for a balanced tree and n for a chain.

At a node, swap its two children, then do the same for each child. An empty node is the base case and returns right away. When every node has been swapped, the whole tree is mirrored.