Skip to main content
CodeOath
← All problems

Problem

Invert Binary Tree

Easy
  • trees
  • recursion

Flip a binary tree from left to right. Every node swaps its left and right children, all the way down, and you return the root of the flipped tree.

Trees in this problem are written as a level-order array: the values row by row from the top, each row from left to right, with null for a missing child. A missing child has no entries beneath it, and trailing nulls are left out.

Example 1
Input
root = [8, 3, 5, 2, 6, 4, 9]
Output
[8, 5, 3, 9, 4, 6, 2]
Explanation

the children of every node trade places. 8 ends up with 5 on its left and 3 on its right, and each of those swaps its own children in turn.

Example 2
Input
root = [1, 2, null, 3]
Output
[1, null, 2, null, 3]
Explanation

node 1 has only a left child. After the flip it has only a right child, and the same happens one level down.

Example 3
Input
root = []
Output
[]
Explanation

an empty tree stays empty.

Constraints:

  • 0 <= number of nodes <= 200
  • -1000 <= node value <= 1000

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.