Invert Binary Tree
Easy· DFS
Problem
Mirror a binary tree so that every node's left and right children are swapped, all the way down. Return the root of the mirrored tree.
Examples
Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]
Each level reads right-to-left after the flip.
Input: root = [2,1,3]
Output: [2,3,1]
Constraints
- • 0 <= number of nodes <= 100
- • -100 <= Node.val <= 100
Hints & approach
Hint 1
Mirroring the whole tree means mirroring each subtree too.
Hint 2
At each node, swap its two children, then recurse into both.
Approachtry the hints first
Visit every node (DFS or BFS) and swap its left and right pointers. With recursion, invert both subtrees and assign them to the opposite sides. The order of swapping versus recursing does not matter as long as each node is swapped exactly once.
Time O(n) · Space O(h)