Will the Mobile Hang Straight

Easydepth-first searchAlso known as Symmetric Tree

A toy maker builds hanging mobiles for babies' rooms. Each charm hangs from a hook, and from each charm up to two arms reach out, a left arm and a right arm, each holding another charm. The toy maker records a mobile as a binary tree of charm weights in grams.

A mobile hangs straight only if its two halves are mirror images: the left half, seen in a mirror, matches the right half charm for charm and arm for arm. The toy maker wants a quick check before gluing anything.

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

Make a mirrored copy of the whole tree, then compare the copy with the original node by node. It is correct and O(n), but it builds a second tree of n nodes just to throw it away.

A tempting shortcut is wrong: checking that each level's weights read the same forwards and backwards. The second example has levels 6, then 2 2, then 4 4, which all look fine, but the 4s hang on the wrong arms. Missing children matter, and comparing the two halves directly takes care of 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