Menu
CoddyTech

Binary Tree Right Side View

The array root holds a binary tree. The root sits at index 0, the children of the node at index i sit at 2*i+1 (left) and 2*i+2 (right), -1 marks an empty spot, and extra -1 entries may trail at the end.

Look at the tree from its right side. Each level shows you exactly one node, the one furthest right, and blocks the rest. List those values from the root's level down to the deepest one.

Function

rightSideView(root: integer-array) → integer-array
rootinteger-array
the tree in heap order, with -1 for an empty spot
Returnsinteger-array
the rightmost value of every level, top level first

Constraints

  • 1 ≤ root.length ≤ 32767
  • Each root[i] is -1 or a value with 0 ≤ root[i] ≤ 104.
  • The node values are distinct.
  • root[0] is never -1, so the tree has at least one node.
  • The array may end with extra -1 entries past the last node.
  • Both children of an empty spot are empty too, and the tree has at most 14 levels.

Examples

Input
root = [5, 2, 9, 7, 4, -1, 1, -1, 3]
Output
[5, 9, 1, 3]
Explanation
From the right you see 5, 9 and 1 (index 6). The fourth level holds only 3, at index 8 under 7 in the left subtree. Nothing on the right reaches that deep, so 3 is visible.
challenge icon

Follow-up

How would you get the right side view of a tree in which every node can have any number of children, stored as a list from left to right?

Reset code
def rightSideView(root):
    # Write code here

Test #1

Test #2

Test #3

Argument

root = [5, 2, 9, 7, 4, -1, 1, -1, 3]

Expected Output

[5, 9, 1, 3]