AcWing 45. 之字形打印二叉树
原题链接
中等
作者:
Value
,
2020-09-15 11:02:21
,
所有人可见
,
阅读 362
/**
* 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:
struct node{
TreeNode *p;
int step;
};
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<node> qu;
qu.push({root, 1});
vector<int> tmp;
int cur = 1;
while(!qu.empty()){
node now = qu.front();
qu.pop();
if(now.step == cur) tmp.push_back(now.p->val);
else{
if(tmp.size() != 0){
if(cur % 2 == 0) reverse(tmp.begin(), tmp.end());
res.push_back(tmp);
cur = now.step;
tmp.clear();
}else cur = now.step;
tmp.push_back(now.p->val);
}
if(now.p->left) qu.push({now.p->left, now.step + 1});
if(now.p->right) qu.push({now.p->right, now.step + 1});
}
if(tmp.size() != 0){
if(cur % 2 == 0) reverse(tmp.begin(), tmp.end());
res.push_back(tmp);
}
return res;
}
};