//103. Binary Tree Zigzag Level Order Traversal
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]
]
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if(root==NULL){
return res;
}
queue<pair<TreeNode*,int>> q;
q.push(make_pair(root,0));
while(!q.empty()){
TreeNode* node=q.front().first;
int level=q.front().second;
q.pop();
if(res.size()==level){
res.push_back(vector<int>());
}
assert(level<res.size());
res[level].push_back(node->val);
if(node->left){
q.push(make_pair(node->left,level+1));
}
if(node->right){
q.push(make_pair(node->right,level+1));
}
}
for(int i=0;i<res.size();i++){
if(i%2 && res.size()>1){
reverse(res[i].begin(),res[i].end());
}
}
return res;
}
};