题解 | 按Z字形打印二叉树
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
使用队列以及reverse()函数
/*
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>> vec;
vector<int> v;
bool flag=true;
if(pRoot==NULL){
return vec;
}
queue<TreeNode*> q;
q.push(pRoot);
while(!q.empty()){
int len=q.size();
for(int i=0;i<len;++i){
TreeNode *t=q.front();
q.pop();
if(!t){//考虑出现空节点情况
continue;
}
q.push(t->left);
q.push(t->right);
v.push_back(t->val);
}
if(flag){
flag=false;
}
else{
reverse(v.begin(),v.end());
flag=true;
}
if(v.size()){
vec.push_back(v);
}
v.clear();
}
return vec;
}
};