Invert Binary Tree

EasyTrees

Given the root of a binary tree, swap every node’s left and right children, all the way down, and return the root.

On this page a tree is written in level order, top to bottom and left to right, with null where a child is missing: [6, 3, 8, 1] is 6 with children 3 and 8, and 3 with a left child 1.

Examples

Example 1
Input:  root = [6, 3, 8, 1, 4, 7, 9]
Output: [6, 8, 3, 9, 7, 4, 1]

Every left and right child swap places, so each level reads backwards.

Example 2
Input:  root = [10, 5, 15]
Output: [10, 15, 5]

The root’s two children swap.

Constraints

  • The tree has 0 to 100 nodes.
  • -100 ≤ node.val ≤ 100

Stuck?

Hint 1

Inverting a tree is: swap the root’s two children, then invert each of them.

Hint 2

A queue works too, level by level, if you would rather not recurse.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 8 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur