思路:
根下面这道题一样,就是把res中奇数的vector反转
参考
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
//跟上一个题一样,把res中奇数vector反转
vector<vector<int>> res;
queue<TreeNode*> q;
if(root) q.push(root);
while(q.size()){
int len=q.size();
vector<int> level;
while(len--){
auto t = q.front();
q.pop();
level.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
res.push_back(level);
}
for(int i=0;i<res.size();i++){
if(i%2){
reverse(res[i].begin(),res[i].end());
}
}
return res;
}
};
评论区