FastPrepZigzag Level-Order Traversal

Zigzag Level-Order Traversal

Flipkart logoFlipkart● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Return the values of a binary tree level by level in zigzag order.

Read the root level from left to right, the next level from right to left, and continue alternating direction at every level. Return an empty matrix when root is null.

Function

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

Examples

Example 1

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

The traversal alternates left-to-right, right-to-left, then left-to-right.

Example 2

root = [1]return = [[1]]

A one-node tree has one level.

Example 3

root = []return = []

An empty tree produces no levels.

Constraints

  • The tree contains between 0 and 2000 nodes.
  • -100000 <= node.val <= 100000

Source note: The source image is a source-neutral excerpt of the author-reported prompt.

More Flipkart problems

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