You're handed the root of a binary tree. Produce its mirror image: at every node, the left and right subtrees trade places. Return the root of the mirrored tree (mutating the tree in place is fine).
If the input is empty (root is null), return null.
Examples
Input
root = [4, 2, 7, 1, 3, 6, 9]Output
[4, 7, 2, 9, 6, 3, 1]Every node's children swap: 4's children 2 and 7 trade places, then their children trade places too, all the way down.
Input
root = [2, 1, 3]Output
[2, 3, 1]A single swap at the root mirrors the whole tree.
Input
root = []Output
[]An empty tree is its own mirror.
Constraints
0 ≤ number of nodes ≤ 100-100 ≤ Node.val ≤ 100
The explainer is the good part.
Sign in for the full intuition build-up, every approach from naive to optimal with complexity analysis, progressive hints, and commented solutions in Python, JavaScript, and Java. All free.
Want a taste first? Try a free sample: Two Sum or Valid Parentheses.