Invert Binary Tree
L7 Medium Trees
Concept
Tree problems beg for recursion: solve the children first, then combine their answers at the current node.
Given the root of a binary tree, mirror it vertically by swapping the left and right child of every node. Return the root of the inverted tree.
Examples
▸ root = [4, 2, 7, 1, 3, 6, 9]
→ [4, 7, 2, 9, 6, 3, 1]
▸ root = [2, 1, 3]
→ [2, 3, 1]
▸ root = []
→ []
Progressive Hints
Hint 1 · Nudge
Swap at this node, then trust the same recipe on each child.
Hint 2 · Plan
If the root is nil, return nil. Invert both children, then swap the left and right children, and return the root.
Hint 3 · Approach
If root is nil, return nil. Recurse into both children first, then swap them: root.left and root.right trade places. Return root.
All hints are out. Take a breath and give it a shot.
Output
// Run your code to see the output here.