AcWing 45. 之字形打印二叉树
原题链接
中等
作者:
疾风劲草
,
2021-07-17 23:24:28
,
所有人可见
,
阅读 184
/**
* 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:
//1. 队列中存的是这层TreeNode * while循环 不断访问该层元素存入vector
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
vector<vector<int>>res;
if(!root)
return res;
queue<TreeNode *>que_;
que_.push(root);
int ceng=0;
while(!que_.empty())
{
ceng++;
vector<int>vec;
int num=que_.size();
while(num--)
{
TreeNode *tmp=que_.front();
vec.push_back(tmp->val);
if(tmp->left)
que_.push(tmp->left);
if(tmp->right)
que_.push(tmp->right);
que_.pop();
}
if(ceng%2==0)
reverse(vec.begin(),vec.end());
res.push_back(vec);
}
return res;
}
};