Menu
CoddyTech

Binary Tree Level Order Traversal

The array tree 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.

Return the node values level by level: one list per level, from the root down to the deepest level, each with its values from left to right.

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
Index 3 is empty, so 9 has only a right child, 6. The third level is 6, 8, 5, and the 3 at index 9, below 6, is alone on the fourth.
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 #1

Test #2

Test #3

Argument

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

Expected Output

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