Menu
CoddyTech

Binary Tree Zigzag Level Order Traversal

You get a binary tree stored in the array root. The root sits at index 0, the children of 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 in zigzag order: the root's level from left to right, the next from right to left, and so on, alternating down to the deepest level. This is also called a spiral level order traversal.

Function

zigzagLevelOrder(root: integer-array) → integer-2d-array
rootinteger-array
the tree in heap order, with -1 for an empty spot
Returnsinteger-2d-array
one list of values per level, top level first, alternating between left to right and right to left

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 = [8, 12, 5, 1, 9, -1, 14, -1, -1, 4, 2, -1, -1, 11]
Output
[[8], [5, 12], [1, 9, 14], [11, 2, 4]]
Explanation
Read left to right, the levels are 8; 12, 5; 1, 9, 14; 4, 2, 11. Levels 1 and 3 run backwards: [5, 12] and [11, 2, 4].
challenge icon

Follow-up

Can you put every value straight into its final place in its row, with no reversing and no second stack?

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

Test #1

Test #2

Test #3

Argument

root = [8, 12, 5, 1, 9, -1, 14, -1, -1, 4, 2, -1, -1, 11]

Expected Output

[[8], [5, 12], [1, 9, 14], [11, 2, 4]]