Invert a tree
Standard · Write code · about 8 min
Given the root of a binary tree, invert it: swap the left and right child of every node, so the tree becomes its mirror image. Return the root of the inverted tree.
Example 1
Input:
[[4,2,7,1,3,6,9]]
Output:
[4,7,2,9,6,3,1]
Every left child becomes a right child and the other way round.
Example 2
Input:
[[2,1,3]]
Output:
[2,3,1]
Constraints
- 0 ≤ number of nodes ≤ 1,000
- -1,000 ≤ Node.val ≤ 1,000
- The tree is given in level order; null marks a missing child
Learn the idea first: Recursive problems on trees: height, size, mirror, paths, a visual lesson.
More Recursive problems on trees: height, size, mirror, paths problems
- Who reports first? Warm-up
- Complete the node counter Warm-up
- Max depth Standard
- Path sum Standard
- Same tree Standard
- Fix the height function Standard
- Diameter of a tree Challenge