103. 二叉树的锯齿形层次遍历 - 力扣(LeetCode)
就是层次遍历加一个标志位记录是否需要反转即可
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> q;
q.push(root);
int flag = 1;
while(!q.empty()){
int n = q.size();
vector<int> tmp;
for(int i = 0; i < n; ++i){
auto cur = q.front(); q.pop();
tmp.push_back(cur->val);
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
if(flag) res.push_back(tmp);
else res.push_back(vector<int>(tmp.rbegin(), tmp.rend()));
flag = !flag;
}
return res;
}
};