Acrobats From the Wings

Mediumbreadth-first searchAlso known as Binary Tree Right Side View

A circus troupe builds a human tower: each acrobat can hold up to two others, one per shoulder. It is recorded as a binary tree of the acrobats' numbers. The floor acrobat is the root, and a node's children stand on its shoulders.

The stage manager watches from the right-hand wing and sees only the acrobat nearest that wing on each row. The lighting cue sheet needs exactly those numbers.

Your task

Write seenFromWing(root). For each level of the tree, take the rightmost node. Return their values starting at the root's level (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], with null marking 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

The rows are [7], [3, 9], [1, 5] and [4]. Acrobats 1 and 5 both stand on 3's shoulders, and 9 holds nobody. The rightmost acrobat of each row is 7, 9, 5 and 4. Following right shoulders alone would stop after 7 and 9.

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

Row 3 holds only acrobat 4, on the far left, but nobody stands to its right, 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 walks down right shoulders only: root, root.right, root.right.right. It fails when the tower's right side is shorter than its left, as in the first example.

A correct but slow fix walks down from the root again for each row number to collect that row. Up to 500 fresh walks over 1,000 acrobats repeat 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