Invert Binary Tree

You are given the root of a binary tree. Invert it: turn it into its mirror image, so that at every node the left and right children trade places. Return the root of the inverted tree.

You may rearrange the existing nodes in place or build new ones; the tests read the tree you return.

Trees are shown in level order (row by row, left to right, null for a missing child), but your function receives and returns TreeNode objects.

Constraints

  • The tree has between 0 and 100 nodes.
  • -100 <= Node.val <= 100

Examples

Example 1

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

Every node's children are swapped, so each level reads right to left: [5], [8, 3], [9, 7, 4, 1].

Example 2

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

The root keeps its place; its two children trade sides.

Example 3

Input: root = []
Output: []

Inverting an empty tree gives an empty tree.

JavaScript you'll use: Recursion, the call stack and memoization Destructuring, spread and rest

/**
 * Tree nodes are provided (you don't need to define them):
 * class TreeNode { constructor(val = 0, left = null, right = null) { this.val = val; this.left = left; this.right = right; } }
 */
/**
 * @param {TreeNode | null} root
 * @return {TreeNode | null}
 */
function invertTree(root) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.