Will the Mobile Hang Straight

Easydepth-first searchAlso known as Symmetric Tree

A toy maker builds hanging mobiles for babies' rooms. From each charm, up to two arms (left and right) each hold another charm. A mobile is recorded as a binary tree of charm weights in grams.

A mobile hangs straight only if its left half, seen in a mirror, matches its right half charm for charm and arm for arm. The toy maker wants to check before gluing.

Your task

Write hangsStraight(root). Return true if the tree is a mirror image of itself around its centre line, and false otherwise. The weights must match as well as the shape.

An empty mobile counts as straight. Trees are shown in level order, like [6, 2, 2, 4, 9, 9, 4], where null marks a missing child. Your function receives real TreeNode objects with val, left and right.

hangsStraight(root: TreeNode) → bool

Examples

Example 1
Input
root = [6, 2, 2, 4, 9, 9, 4]
Output
true
Why

Under the 6 there is a 2 on each side. The left 2 holds 4 then 9. The right 2 holds 9 then 4. In a mirror, the outer charms (4 and 4) face each other and the inner charms (9 and 9) face each other, so it hangs straight.

Example 2
Input
root = [6, 2, 2, null, 4, null, 4]
Output
false
Why

Both 2s hold a 4 on their right arm. The two halves are identical copies, not mirror images: the left 4 is on the inside, the right 4 is on the outside. The mobile tips.

Constraints

  • 0 ≤ number of charms ≤ 1,000
  • 1 ≤ weight ≤ 1,000
  • The tree is at most 500 levels deep.
Start with brute force

Build a mirrored copy of the tree and compare it with the original node by node. Correct and O(n), but it builds a second tree just to throw it away.

A tempting shortcut is wrong: checking that each level's weights read the same both ways. The second example's levels are 6, then 2 2, then 4 4, all fine, but the 4s hang on the wrong arms. Missing children matter, and comparing the halves directly handles them.

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