Practice49:
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
S1
牛客解题之一,模板法
/*
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)return res;
queue<TreeNode*> q;
q.push(pRoot);
int level=0;
while(!q.empty()){
int sz = q.size();
vector<int> vs;
while(sz--){
TreeNode* mid = q.front();
vs.push_back(mid->val);
q.pop();
if(mid->left)q.push(mid->left);
if(mid->right)q.push(mid->right);
}
++level;
if(!(level&1)){
reverse(vs.begin(),vs.end());
}
res.push_back(vs);
}
return res;
}
};