Iron-On Transfer Flip

Easydepth-first searchAlso known as Invert Binary Tree

A print shop is making family-reunion T-shirts. The design is a family tree of boxes, each holding a person's id, with at most two children under each box. Iron-on transfer paper prints mirror-image, so the design must be flipped left to right first. Flipping does more than swap the two halves at the top: every branch, all the way down, ends up the other way round.

Your task

Write mirrorDesign(root). Turn the tree into its mirror image: at every node, the left subtree becomes the right subtree and the right becomes the left. Return the root of the mirrored tree. You may change the tree in place.

An empty tree stays empty. Trees are shown in level order, like [5, 3, 8, 1, 4, null, 9], where null marks a missing child. Your function receives and returns real TreeNode objects with val, left and right.

mirrorDesign(root: TreeNode) → TreeNode

Examples

Example 1
Input
root = [5, 3, 8, 1, 4, null, 9]
Output
[5, 8, 3, 9, null, 4, 1]
Why

5 stays on top and its children swap: 8 left, 3 right. Below them the same happens: 9 moves to 8's left, and 3's children become 4 then 1. The bottom row 1, 4, 9 now reads 9, 4, 1.

Example 2
Input
root = [1, 2]
Output
[1, null, 2]
Why

A lone left child becomes a lone right child, so the swap must also work when the other child is missing.

Constraints

  • 0 ≤ number of people ≤ 1,000
  • -100,000 ≤ id ≤ 100,000
  • The tree is at most 500 levels deep.
Start with brute force

You could read the tree into rows, reverse each row, and rebuild. But that means keeping every empty slot, and the slots double at every level, so a lopsided tree with 1,000 people can have rows far bigger than the tree. You never need the rows: swapping the two child pointers at every node, once, flips the whole picture in O(n) with no copies.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code