Skip to content
RED SAGSkills
medium30 ptstreebfs

What You See From the Right

A binary tree is given as a level-order array: tree[0] is the root, then the children of each real node are listed left to right, level by level. A missing child is written as null, and the children of a missing node are not listed at all. For example [1,2,3,null,4] is root 1 with children 2 and 3, where 2 has only a right child 4.

Imagine standing to the right of the tree and looking at it. On every level you only see the right-most node. Return the values you see, from the top level down.

Example 1

Input: tree = [1,2,3,null,5,null,4]
Output: [1,3,4]
Explanation: Levels are [1], [2,3], [5,4]; the right-most of each is 1, 3, 4.

Example 2

Input: tree = [1,null,3]
Output: [1,3]

Constraints

  • 0 <= number of nodes <= 10^4
  • -100 <= node value <= 100
Hint 1

Process the tree level by level with a queue.

Hint 2

The last node of each level is the one visible from the right.

Discussion 0

Join free to post in the discussion.

Good practice for: Frontend Developer, Backend Developer, Full Stack Developer, Game Developer, Mobile App Developer

Run checks your code on 2 sample tests. Submit runs all 7 tests, including hidden ones, and earns points. Use console.log to debug. Python's first run can take a few seconds while it starts.