Menu
CoddyTech

Binary Tree Level Order Traversal

You get a binary tree stored in the array 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 the array may end with extra -1 entries.

Return the node values level by level: a list holding the root's value, then a list with the values one level down, from left to right, and so on to the deepest level.

Function

levelOrder(tree: integer-array) → integer-2d-array
treeinteger-array
the tree in heap order, with -1 for an empty spot
Returnsinteger-2d-array
one list of values per level, top level first, each from left to right

Constraints

  • 1 ≤ tree.length ≤ 32767
  • Each tree[i] is -1 or a value with 0 ≤ tree[i] ≤ 1000.
  • tree[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 depth is at most 14.

Examples

Input
tree = [4, 9, 2, -1, 6, 8, 5, -1, -1, 3]
Output
[[4], [9, 2], [6, 8, 5], [3]]
Explanation
The root 4 has children 9 and 2 at indexes 1 and 2. Index 3 is empty, so the third level is 6 (index 4, under 9), then 8 and 5 (indexes 5 and 6, under 2). The 3 at index 9 is the left child of 6, alone on the fourth level.

lock icon+15 hidden tests on Submit

challenge icon

Follow-up

Can you return the levels in zigzag order, the first from left to right, the second from right to left, and so on, without sorting any level?

Reset code
def levelOrder(tree):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

tree = [4, 9, 2, -1, 6, 8, 5, -1, -1, 3]

Expected

[[4], [9, 2], [6, 8, 5], [3]]