题解 | #按之字形顺序打印二叉树#
按之字形顺序打印二叉树
http://www.nowcoder.com/practice/91b69814117f4e8097390d107d2efbe0
/*
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* head) {
if(head==nullptr) return {};
queue<TreeNode *> q;
vector<vector<int>> res;
vector<int> temp;
q.push(head);
int high=1;
while(!q.empty()){
int sz=q.size();
for(int i=0;i<sz;i++){
TreeNode* p=q.front();
q.pop();
temp.push_back(p->val);
if(p->left) q.push(p->left);
if(p->right) q.push(p->right);
}
if(high%2==0) reverse(temp.begin(),temp.end());
high++;
res.push_back(temp);
temp.clear();
}
return res;
}
};