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] ]
在102的基础上稍加改动即可
class Solution { public: vector<vector<int>> zigzagLevelOrder(TreeNode* root) { queue<TreeNode*> q; queue<int> q2; vector<vector<int> > ans; if(root==NULL) return ans; q.push(root);q2.push(0); vector<int> res; int j=-1; int tag = 0; while(!q.empty()) { TreeNode* term = q.front(); int i = q2.front(); if(i==j+2) { if(tag==1) { vector<int> a; for(int i=res.size()-1;i>=0;i--) { a.push_back(res[i]); } tag=0; ans.push_back(a); } else { ans.push_back(res); tag=1; } res.clear(); j++; } res.push_back(term->val); q.pop();q2.pop(); if(term->left!=NULL) { q.push(term->left);q2.push(i+1);} if(term->right!=NULL) { q.push(term->right);q2.push(i+1);} } if(!res.empty()) { if(tag==1) { vector<int> a; for(int i=res.size()-1;i>=0;i--) { a.push_back(res[i]); } tag=0; ans.push_back(a); } else ans.push_back(res); } return ans; } };