用一个变量标记当前层数,如果是偶数层就反转vector
/**
* 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;
queue<TreeNode*> q;
q.push(root);
int i = 1;// 记录当前层数
while(q.size()) {
int len = q.size();
vector<int> lev;
for (int j = 0; j < len; j++) {
auto t = q.front();
q.pop();
lev.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
if (i % 2 == 0) reverse(lev.begin(), lev.end());
res.push_back(lev);
i++; //更新层数
}
return res;
}
};