/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
if(pRoot==nullptr) return res;
bool flag=true;//之字形标记位
queue<TreeNode*> que;
que.push(pRoot);
while(que.size()!=0){
int size=que.size();
vector<int> path;
while(size--){
auto temp=que.front();
path.push_back(temp->val);
que.pop();//队列用完一个元素,要pop()下
if(temp->left) que.push(temp->left);
if(temp->right) que.push(temp->right);
}
//之字形反转
if(flag==false){
reverse(path.begin(),path.end());
flag=true;
}else flag=false;
res.push_back(path);
}
return res;
}
};
NC14 按之字形顺序打印二叉树(C++)- 中等、栈、树、队列
最新推荐文章于 2024-08-27 21:01:50 发布