All problems

Invert Binary Tree

Easy · tree dfs

You are given the root of a binary tree. Return the mirror image of the tree: at every node, the left and right subtrees trade places, all the way down.

Return the root of the mirrored tree. You may rebuild the tree or rearrange the existing nodes, whichever you prefer. An empty tree stays empty.

Examples

Example 1

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

Output: [4, 7, 2, 9, 6, 3, 1]

Node 4 now has 7 on its left and 2 on its right, and the same swap happens inside both subtrees.

Example 2

Input: root = [2, 1, 3]

Output: [2, 3, 1]

Example 3

Input: root = [1, null, 2]

Output: [1, 2]

A lone right child becomes a lone left child.

Constraints