Skip to content
BytePatterns

Zigzag Level Walk

MediumTrees & BST#bfs#level-order~30m

Problem

Given the root of a binary tree, collect its values level by level, but alternate the reading direction. The top level is read left to right, the next level right to left, and so on down the tree. Return one list per level, and an empty result for an empty tree.

Examples

Input:  tree = 3 with children 9 and 20, where 20 has children 15 and 7
Output: [[3], [20, 9], [15, 7]]
Why:    the middle level is reversed, the bottom level returns to normal
Input:  tree = 1 alone
Output: [[1]]
Why:    a single level is read left to right
Input:  tree = empty
Output: []
Why:    edge case, there are no levels to report

Hints

0 / 3

Stuck on the idea rather than the code? Tree Traversals covers it.