103 Binary Tree Zigzag Level Order Traversal
Given a binary tree, return thezigzag level ordertraversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree[3,9,20,null,null,15,7]
,
return its zigzag level order traversal as:
Approach:
We can first reduce this problem performing a level order traversal that meet the requirement of allocating a new vector per level. To do this, we follow two conditions. (1) If the element in the queue is null, then push in another nullptr. Here, we also know that the temporary 1d vector has finished its insertions, so it can be pushed back to the main 2d vector, and reset. Additionally, we flip a switch the tells is that the next insertion should be pushed back in reverse order. (2) Otherwise, do the usual bits of adding the left and right nodes.
How it works:
Consider the following tree:
We would follow roughly through the following process:
As we can see, every null that follows will be appropriate.
Limitations
Pushing back to the front of a vector is a bad idea! Ideally, I would have returned vector of lists.
Last updated