Skip to content
EasyTreesAI interview only

Invert Binary Tree

Asked atgoogleamazonmetamicrosoftapplebloomberg

01 · Problem

You are handed the root of a binary tree. Flip the tree into its mirror image: at every node, the left child becomes the right child and vice versa. Return the root of the flipped tree.

The tree is given in level-order, with null marking a missing child. The expected output is the level-order serialization of the mirrored tree (trailing nulls omitted).

02 · Examples

Example 01
     4              4
   /   \          /   \
  2     7   =>   7     2
 / \   / \      / \   / \
1   3 6   9    9   6 3   1
Input
root = [4,2,7,1,3,6,9]
Output
[4,7,2,9,6,3,1]

Swapping children at every level reverses each level: [2,7] becomes [7,2] and [1,3,6,9] becomes [9,6,3,1].

Example 02
Input
root = [2,1,3]
Output
[2,3,1]

The root's two children trade places.

Example 03
Input
root = []
Output
[]

An empty tree mirrors to an empty tree.

03 · Constraints

  • 01The number of nodes in the tree is in the range [0, 100].
  • 02-100 <= Node.val <= 100
  • 03The tree height is at most 100, and the tree may be fully skewed.
  • 04Node values are not necessarily unique.

04 · Optimal complexity

Time
O(n)
Space
O(h)
05 · Two ways to work on it

Practice it alone or rehearse it as an interview.

Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.