48. Invert Binary Tree

Easy · Binary Tree

Given the root of a binary tree, invert the tree (mirror it left-to-right) and return its root.

Inverting a binary tree means swapping the left and right children of every node in the tree recursively, producing a mirror image of the original tree.

The tree is encoded as a level-order (BFS) array where `null` represents a missing node. Your answer should also be returned as a level-order array with `null` for missing nodes.

Examples

Example 1
Input: [4, 2, 7, 1, 3, 6, 9]
Output: [4, 7, 2, 9, 6, 3, 1]
Explanation: The original tree has 2 on the left and 7 on the right of root 4. After inversion, 7 moves to the left and 2 to the right. Their children are also swapped recursively.
Example 2
Input: [1, 2]
Output: [1, null, 2]
Explanation: The original tree has 2 as the left child of 1. After inversion, 2 becomes the right child of 1, and the left child is null.

Constraints