Menu
CoddyTech

Top View of Binary Tree

You get a binary tree stored in the array root in heap order: the root at index 0, the children of index i at 2*i+1 (left) and 2*i+2 (right), and -1 for an empty spot.

The root is in column 0; a left child sits one column left of its parent and a right child one column right. From above you see the shallowest node of each column; on a tie, the one first in its level from left to right (the smaller index). Return the values you see, from the leftmost column to the rightmost.

Function

topView(root: integer-array) → integer-array
rootinteger-array
the tree in heap order, with -1 for an empty spot
Returnsinteger-array
the value seen from above in each column, leftmost column first

Constraints

  • 1 ≤ root.length ≤ 32767
  • Each root[i] is -1 or a value with 0 ≤ root[i] ≤ 104, and no value appears twice.
  • 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, 4, 7, 1, 6]
Output
[4, 2, 5, 9, 6]
Explanation
From left to right the columns hold 4 (column -2), 2 (-1), the root 5 (0), 9 (1) and 6 (2). 7 and 1 also sit in column 0, but the root is above them.
challenge icon

Follow-up

With node objects instead of an array, there is no index to settle a tie. How would you state the tie rule, and does your breadth-first code change?

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

Test #1

Test #2

Test #3

Argument

root = [5, 2, 9, 4, 7, 1, 6]

Expected Output

[4, 2, 5, 9, 6]