AcWing 45. 之字形打印二叉树
原题链接
中等
C++ 代码
/**
* 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);
q.push(nullptr);
vector<int> line;
int flag = 1;
while(!q.empty()){
auto t = q.front();
q.pop();
if(!t){
//偶数
if(!(flag & 1)) reverse(line.begin(), line.end());
flag ++ ;
res.push_back(line);
line.clear();
if(q.size()) q.push(nullptr);//加if是为了判断最后一个nullptr
}else{
line.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return res;
}
};