Practice · Trees · 6 of 12

A Binary Tree Seen from the Right

You are given root, the root of a binary tree (or nothing, for an empty tree).

Imagine standing to the right of the tree and looking at it: on each level, you see only the rightmost node. Return the values you see, from the top level down. An empty tree gives [].

Trees are written in level order, row by row from the top, with null where a node is missing: [4, 2, 7, null, 3] is 4 at the root, 2 and 7 below it, and 3 as the right child of 2.

Example 1

Input
root = [8, 4, 9, 2, 6]
Output
[8, 9, 6]
9 hides 4 on the second level, and 6 hides 2 on the third.

Example 2

Input
root = [1, 2, 3, 4]
Output
[1, 3, 4]
4 is a left child, but nothing on its level is further right, so you can see it.

Constraints

  • The tree holds 0 to 2000 nodes.
  • Every value is between −1000 and 1000.