题目:
代码(首刷自解 2024年4月12日):
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> res;
vector<int> path;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
int count = 1;
while(!q.empty()) {
int size = q.size();
path.clear();
count++;//奇数 左往右 偶数 右往左
while (size--) {
TreeNode* node = q.front();
if (!(count & 1)) {
path.push_back(node->val);
} else {
path.insert(path.begin(), node->val);
}
q.pop();
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.push_back(path);
}
return res;
}
};
代码(二刷debug看解析 2024年8月5日)
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
// 队列存Node
vector<vector<int>> res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
vector<int> temp;
temp.reserve(size);
while(size--) {
auto node = q.front();
q.pop();
if (0 == (res.size() & 1)) {
temp.emplace_back(node->val);
} else {
temp.insert(temp.begin(), node->val);
}
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
res.push_back(temp);
}
return res;
}
};