Acrobats From the Wings

Mediumbreadth-first searchAlso known as Binary Tree Right Side View

A circus troupe builds a human tower. One acrobat stands on the floor, and every acrobat can hold up to two others on their shoulders, one on the left shoulder and one on the right. Each acrobat wears a number, and the tower is recorded as a binary tree: the floor acrobat is the root, and a node's children are the acrobats on their shoulders.

The stage manager stands in the right-hand wing, looking across the stage at the tower. On each row of the tower, the manager can only see the acrobat nearest the right wing; everyone else on that row is hidden behind them. The lighting cue sheet needs exactly the numbers the manager can see.

Your task

Write seenFromWing(root). For each level of the tree, take the rightmost node on that level. Return their values starting with the root's level (the acrobat on the floor) and moving up one row at a time.

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

seenFromWing(root: TreeNode) → int[]

Examples

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

Row 1 is just 7. Row 2 is 3 and 9; 9 is nearest the wing. Row 3 is 1 and 5, both on 3's shoulders, because 9 holds nobody; 5 is visible. Row 4 is only 4, standing on 5. Following right shoulders alone would stop after 7 and 9 and miss 5 and 4.

Example 2
Input
root = [1, 2, 3, 4]
Output
[1, 3, 4]
Why

Row 2 shows 3. Row 3 has only acrobat 4, on the far left of the tower, but nobody stands to its right on that row, so the manager sees it.

Constraints

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

The quick guess is to walk down the right shoulders from the floor: root, root.right, root.right.right, and so on. It fails as soon as the right side of the tower is shorter than the left, as in the first example.

A correct slow fix is to compute, for each row number, every acrobat on that row by walking down from the root again, then pick the rightmost. Starting a fresh walk for each of up to 500 rows over 1,000 acrobats repeats a lot of work. One level-by-level pass finds every row at once.

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