AcWing 45. 精简版 不用reverse
原题链接
中等
作者:
mui
,
2020-07-29 05:22:48
,
所有人可见
,
阅读 520
class Solution {
public:
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
vector<vector<int>> res {};
if (!root) return res;
queue<TreeNode*> q {{root}};
bool flag = true;
while (!q.empty()) {
auto size = q.size();
vector<int> vLevel(size);
for (size_t i = 0; i < size; i++) {
auto node = q.front(); q.pop();
auto idx = flag? i : size-1-i;
vLevel[idx] = node->val;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
flag = !flag;
res.emplace_back(move(vLevel));
}
return res;
}
};