Iron-On Transfer Flip

Easydepth-first searchAlso known as Invert Binary Tree

A print shop is making T-shirts for a family reunion. The design is a family tree drawn as boxes, each holding a person's id number, with at most two children under each box. Iron-on transfer paper prints everything mirror-image, so the shop must flip the design left to right before printing.

Flipping a picture does more than swap the two halves at the top. Every family 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 at the top. Its children swap sides: 8 is now on the left, 3 on the right. Below them the same happens: 8's only child 9 moves to its left, and 3's children become 4 then 1. Read left to right, the bottom row was 1, 4, 9 and is now 9, 4, 1.

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

A lone left child becomes a lone right child. The swap must also move a child next to an empty slot, not only swap two existing children.

Constraints

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

Read the tree level by level into rows, reverse each row, and rebuild a tree from the reversed rows. To make that work you have to keep every empty slot in each row, and a lopsided tree with 1,000 people can have rows with far more empty slots than people, because the slots double at every level.

You never need the rows. Mirroring is a purely local change: at each node, swap its two child pointers. Do that at every node once and the whole picture is flipped, in O(n) time with no extra 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