FastPrepBinary Tree Spiral Level Order

Binary Tree Spiral Level Order

Bloomberg LP logoBloomberg LP● MediumNEW GRADPHONE SCREENONSITE INTERVIEW
Learn

Problem statement

Return the values of a binary tree one level at a time in alternating directions.

For this exercise, assume the root level is traversed left to right, the next level right to left, and directions alternate thereafter. Group values by their distance from the root and omit missing children. Preserve node positions even when values repeat. An empty tree returns an empty list.

Function

zigzagLevels(root: TreeNode) → int[][]

Examples

Example 1

root = [3,9,20,null,null,15,7]return = [[3],[20,9],[15,7]]

The root is left-to-right, the second level is right-to-left, and the third returns to left-to-right.

Example 2

root = [1,2,3,4,null,null,5]return = [[1],[3,2],[4,5]]

Null links are skipped; the second level is [3,2] and the third is [4,5].

Example 3

root = []return = []

An empty tree has no levels.

Constraints

  • For this exercise, assume a finite acyclic binary tree with 0 through 500 nodes.
  • -10^6 <= node.val <= 10^6.

More Bloomberg LP problems

See Bloomberg LP hiring insights
public int[][] zigzagLevels(TreeNode root) {
    // Write your code here
}
root[3,9,20,null,null,15,7]
expected[[3],[20,9],[15,7]]
Checking account…