和上一个题目一样,我只是加入了一个flag 值用来标记该行是否时逆向输出
/**
* 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:
bool flag;
vector<vector<int>> a;
vector<int> b;
vector<TreeNode*> reserve;
queue<TreeNode*> q;
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
if(!root) return a;
reserve.push_back(root);
while(reserve.size()){
//将一行的节点全部压入队列
for(auto item : reserve){
q.push(item);
}
//将存储那一行的节点全部清除
while(reserve.size()) reserve.pop_back();
//将队列里面的元素进行遍历
while(q.size()){
TreeNode* t = q.front();
q.pop();
//将这一行的所有元素存储进一维数组
b.push_back(t -> val);
//将这一行的所有的子节点全部存储进reserve
if(t -> left != NULL) reserve.push_back(t -> left);
if(t -> right != NULL) reserve.push_back(t -> right);
}
//将一行的数据存储进二维数组
if(!flag) flag = true;
else{
flag = false;
reverse(b.begin(), b.end());
}
a.push_back(b);
//将b里面的元素清空,为下一行做准备
while(b.size()) b.pop_back();
}
return a;
}
};