题面
题解
和44题一样,在每层末尾加一个nullptr ,就可以实现分层 ,然后加一个计数器,当cnt为奇数时,直接放入res,当cnt为偶数时,将cur翻转,然后放入res
代码
/**
* 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>> printFromTopToBottom(TreeNode *root) {
vector<vector<int>> res;
if (!root) return res;
vector<int> cur;
queue<TreeNode *> q;
q.push(root);
q.push(nullptr);
int cnt = 1;
while (q.size()) {
auto t = q.front();
q.pop();
if (t) {
cur.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
} else {
if (cnt & 1) res.push_back(cur);
else {
reverse(cur.begin(), cur.end());
res.push_back(cur);
}
cnt++;
cur.clear();
if (q.size()) q.push(nullptr);
}
}
return res;
}
};