Invert a Tree

You are given the root of a binary tree. Invert it: swap the left and right child of every node, so the tree becomes its mirror image. Return the root.

Trees in the examples are written level by level, left to right, with null where a child is missing: [1,null,2] is a root 1 with only a right child, 2. [] is an empty tree, with no root at all.

Constraints

  • 0 ≤ number of nodes ≤ 5,000
  • -100 ≤ node value ≤ 100
  • The tree is at most 1,000 levels deep.

Example 1

Input
root = [4,2,7,1,3,6,9]
Output
[4,7,2,9,6,3,1]
Why:

Every level reads backwards: 2 7 becomes 7 2, and 1 3 6 9 becomes 9 6 3 1.

Example 2

Input
root = [2,1,3]
Output
[2,3,1]
Why:

The root's two children swap.

Example 3

Input
root = []
Output
[]
Why:

An empty tree stays empty.

Hints

    Was this a good challenge?

    Solved by
    0
    Submissions
    0
    Accepted
    –