Menu
CoddyTech

Left View of Binary Tree

You get a binary tree as the array root in heap order: the root is at index 0, the children of index i are at 2*i+1 (left) and 2*i+2 (right), and -1 marks an empty spot. The array may end with extra -1 entries.

Stand to the left of the tree. On every level you see one node, the leftmost; the rest of the level hides behind it. Return the values you see, from the top level down.

Function

leftView(root: integer-array) → integer-array
rootinteger-array
the tree in heap order, with -1 for an empty spot
Returnsinteger-array
the leftmost 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 = [3, 8, 5, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, 1]
Output
[3, 8, 6, 1]
Explanation
8 is a leaf, so the third and fourth levels hold only 6 (index 6) and 1 (index 13), both under the right child 5. You see them anyway: [3, 8, 6, 1].
challenge icon

Follow-up

Level d fills indexes 2^d-1 to 2^(d+1)-2. Can you build the view by scanning those ranges, with no queue or recursion? What does that cost on a padded array?

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

Test #1

Test #2

Test #3

Argument

root = [3, 8, 5, -1, -1, -1, 6, -1, -1, -1, -1, -1, -1, 1]

Expected Output

[3, 8, 6, 1]