Swap the left and right child of every node in a binary tree and return the mirrored tree.
Invert Binary Tree
Given the root of a binary tree, create its mirror image by swapping the left and right child of every node in the tree.
You may return the modified tree root after in-place inversion, or a new root representing the inverted tree depending on your implementation style. The structure of the tree after inversion should be the same as if every node's children were exchanged recursively.
Goal
- Traverse every node exactly once.
- Swap each node's left and right subtrees.
- Return the root of the inverted tree.
Input Format
- A binary tree root node is provided in the usual serialized form for the platform.
- Each node contains an integer value and optional left/right child references.
Output Format
- Return the root of the inverted binary tree.
Constraints
- The tree can be empty.
- Node values are not required to be unique.
- Aim for a solution that visits each node once.
Example 1
Input
root = [4,2,7,1,3,6,9]
Output
[4,7,2,9,6,3,1]
Explanation
After inversion, every node's left and right children are swapped. The root stays the same, but its subtrees are mirrored.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.