Invert Binary Tree
EasyTrees
Given the root of a binary tree, invert it and return its root.
Inverting means producing the mirror image: at every node, the left and right children swap places (including when one of them is missing). You may modify the tree in place. The returned tree is checked in level order.
Trees are written in level order: values are listed level by level, left to right, and null marks a missing child (trailing nulls are omitted).
Example 1
- Input:
- root = [1,2,3,null,4]
- Output:
- [1,3,2,null,null,4]
- Explanation
- The root's children swap places, and node 2 keeps its single child, but that child moves from the right side to the left.
Example 2
- Input:
- root = [5,3,8,1,4,7,9]
- Output:
- [5,8,3,9,7,4,1]
- Explanation
- Every level reads backwards after mirroring: 8 and 3 swap, and the bottom row 1, 4, 7, 9 becomes 9, 7, 4, 1.
Example 3
- Input:
- root = [1,2,null,3]
- Output:
- [1,null,2,null,3]
- Explanation
- The tree leans entirely left, so inverting makes it lean entirely right.
Constraints
- The number of nodes is in the range
[0, 100] -100 <= Node.val <= 100