You get the root of a binary tree. Turn the tree into its mirror image: at every node, the left subtree and the right subtree change places.
Change the tree in place and return its root. An empty tree stays empty.
Example 1
Input: root = [5, 3, 8, 1, 4] Output: [5, 8, 3, null, null, 4, 1] Why: 3 and 8 trade sides, and so do 1 and 4 under 3
2 more examples and the constraints
Example 2
Input: root = [6, 9, 2] Output: [6, 2, 9] Why: the root's two children change places
Example 3
Input: root = [] Output: [] Why: there is nothing to swap
Constraints
- 0 ≤ number of nodes ≤ 100
- −100 ≤ Node.val ≤ 100
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- RecursionO(n)
- Swap level by level with a queueO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100 nodes | Verdict |
|---|---|---|---|
| Recursion | O(n) | Shortest code; uses the call stack | |
| Swap level by level with a queue | O(n) | Best; no recursion depth to worry about |
n = number of nodes, h = height of the tree. Both visit each node once.
Edge cases to test
- Empty tree. root is null: return null without touching anything.
- One node. A leaf has nothing to swap; [42] stays [42].
- A one-sided chain. [1, 2, null, 3] leans left and comes back leaning right: [1, null, 2, null, 3].
- Missing children. Swapping a child with null is still a swap: the lone child moves to the other side.
Common mistakes
- Writing
root.left = invert(root.right)and thenroot.right = invert(root.left), which reads the left side after it was overwritten. - Swapping only the root's children and forgetting to mirror the subtrees below.
- Skipping nodes with one child, which leaves that child on the wrong side.
How to talk through it
- 1Clarify. Should I change the tree in place or return a new one? Can the root be null?
- 2State the rule. A mirror swaps the two subtrees at every node, so every node needs one swap.
- 3Give the recursion. Mirror both subtrees, then swap them; O(n) time, O(h) stack.
- 4Offer the queue. The same swaps in BFS order avoid deep recursion on a skewed tree.
- 5Test out loud. Run the empty tree, a single node and a one-sided chain.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?