easyTreesPure DSA~12 min
Mirror Layout Invert
A UI toolkit supports a right-to-left locale by mirroring a layout tree: every node's children swap sides, recursively. Given the layout tree root, return the inverted tree.
Problem
Given the root of a binary tree, invert it — swap the left and right child of every node — and return the new root.
Input
The root of a tree with n nodes (0 ≤ n ≤ 10^4), shown in level order with null for missing children.
Output
The level-order layout of the inverted tree.
Constraints
- 0 ≤ n ≤ 10,000
- Node values fit in a 32-bit int
- Invert in place is acceptable
Examples
Example 1
Input
root = [4, 2, 7, 1, 3, 6, 9]
Output
[4, 7, 2, 9, 6, 3, 1]
Every node's two subtrees swap, mirroring the whole tree.
Example 2
Input
root = [1, 2]
Output
[1, null, 2]
The single left child moves to the right.