Menu
CoddyTech

Bottom View of Binary Tree

The array root holds a binary tree: the root at index 0, the children of index i at 2i+1 (left) and 2i+2 (right), -1 for an empty spot, and possibly extra -1 entries at the end.

The root is in column 0; a left step moves one column left, a right step one column right. Seen from below, each column shows its deepest node, and on a tie the last one on that level read from left to right (the larger index). Return the values you see, leftmost column first.

Function

bottomView(root: integer-array) → integer-array
rootinteger-array
the tree in heap order, with -1 for an empty spot
Returnsinteger-array
the value seen from below 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, 1, 9, 6]
Explanation
Column 0 holds 5 and, two levels down, 7 (index 4) and 1 (index 5). 1 comes later on the shared level, so it shows. Columns -2, -1, 1 and 2 hold 4, 2, 9 and 6.
challenge icon

Follow-up

If a tie on a column's deepest level should return every tied node, left to right, how would the breadth-first version change? What would column 0 of example 1 give?

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

Test #1

Test #2

Test #3

Argument

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

Expected Output

[4, 2, 1, 9, 6]