Invert Binary Tree
easyBlind 75NeetCode 150treesrecursion
Problem
Given the root of a binary tree, produce its mirror image by swapping the left and right child of every node. Return the root of the inverted tree.
Examples
Input: [4, 2, 7, 1, 3, 6, 9]
Output: [4, 7, 2, 9, 6, 3, 1]
Every node's children are swapped.
Input: empty tree
Output: empty tree
Nothing to invert.
Constraints
- • 0 <= number of nodes <= 100
- • -100 <= node value <= 100
Hints(tap to reveal)
- 1. Swap children at each node.
- 2. Recurse into both subtrees.
Optimal approach(spoiler)
- If the node is null, return null.
- Swap the node's left and right children.
- Recurse into both subtrees.
- Return the original root after the swaps propagate.
- O(n) time, O(h) recursion space.
Ready to solve it?
Write your solution in the editor and get an instant AI grade on correctness, edge cases, and complexity.
Practice in the editor