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).
For 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] ]
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> value;
if (root == NULL)
return value;
stack<TreeNode*> level[2];
vector<int> curvalue;
int current = 0;
int next = 1;
level[current].push(root);
while (!level[0].empty() || !level[1].empty())
{
TreeNode* p = level[current].top();
curvalue.push_back(p->val);
level[current].pop();
if (current == 0)
{
if (p->left != NULL)
level[next].push(p->left);
if (p->right != NULL)
level[next].push(p->right);
}
else
{
if(p->right!=NULL)
level[next].push(p->right);
if (p->left != NULL)
level[next].push(p->left);
}
if (level[current].empty())
{
value.push_back(curvalue);
curvalue.clear();
current = 1 - current;
next = 1 - next;
}
}
return value;
}
};