上一篇再加一个条件:先从左往右,再从右往左。。以此类推
/**
* 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>> res;
if(!root)
return res;
queue<TreeNode*> q;
int step = 0;
q.push(root);
while(!q.empty()){
int sz = q.size();
vector<int > tmp;
for(int i=0;i<sz;i++){
TreeNode* node = q.front();
q.pop();
tmp.push_back(node->val);
if(node->left != NULL)
q.push(node->left);
if(node->right != NULL)
q.push(node->right);
}
//奇数step需要翻转一下
//翻转操作如下
if(step & 1){
reverse(tmp.begin(), tmp.end());
}
res.push_back(tmp);
step++;
}
return res;
}
};