Akshay Saini

Posted on

# ZigZag (Spiral) Level Order Traversal π₯ | Amazon Interview Question

Binary Tree Zig-zag Level Order Traversal a.k.a. Spiral Level Order Traversal has been frequently asked in Coding Interviews of Amazon, Google, Microsoft, Facebook, Apple, LinkedIn, Samsung, Walmart, and a lot of other tech giants.

Do give it a try, but what if you're stuck somewhere?
No need to worry. This article contains a working solution to this Leetcode Medium problem using Javascript. β€οΈ

Towards the end of this post, I also have a Youtube video attached, you can also watch a step by step solution there if needed. All the best for your coding Interviews. ππΎ

Problem Statement:

Given a binary tree, return the Zigzag Level Order Traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

Example:
Given binary tree [3,9,20,null,null,15,7],

``````   3
/ \
9   20
/  \
15    7
``````

Return its zigzag level order traversal as:

``````[
[3],
[20,9],
[15,7]
]
``````

Javascript Code:

Below is the Javascript code for this Leetcode Medium problem of Spiral Level Order traversal.

``````var zigzagLevelOrder = function(root) {
let results = [];
const lot = (root, level) => {
if(!root) return;

if(results[level]) results[level].push(root.val);
else results[level] = [root.val];

lot(root.left, level+1);
lot(root.right, level+1);
}
lot(root, 0);
return results.map((b,i)=>(i%2) ? b.reverse(): b);
};
``````

Step by Step Explanation in below Youtube Video:

Below is the Youtube video explaining this frequently asked Interview question of Binary Tree Spiral Level Order Traversal.

If you like this initiative of solving DS/ Algo Coding Interview Problems from Leetcode using Javascript then do give it a thumbs up and comment down your feedback.

You can also check out this Github Repository for all the code and video links in this #DSinJS series on Youtube.

Cheers,
Akshay Saini
https://akshaysaini.in