204. Zig Zag or Spiral Traversal

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

Example 1:

Input : root = [1, 2, 3, null, 4, 8, 5]

Output : [ [1] , [3, 2], [4, 8, 5] ]

Explanation : So at root we move from left to right.

At next level we move in opposite direction i.e. from right to left.

At next level again reverse the traversal i.e. from left to right.

Example 2:

Input : root = [3, 9, 20, null, null, 15, 7]

Output : [ [3] , [20, 9], [15, 7] ]

Explanation : So at root we move from left to right.

At next level we move in opposite direction i.e. from right to left , from 20 to 9.

At next level again reverse the traversal i.e. from left to right, from 15 to 7.

Now Your Turn!

Pick the correct output for the given input

Input : root = [5, 1, 2, 8, null, 4, 5, null, 6]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 104
  • -103 <= Node.val <= 103

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution {
public:
vector<vector<int> > zigzagLevelOrder(TreeNode* root) {
//your code goes here
}
};
Test Case

Input:

Root