题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
//方法1:利用队列和level标记,确定是对vec采用push_back()还是insert()操作
//insert()操作复杂度较高
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> ans;
if(pRoot==NULL) return ans;
queue<TreeNode*> q;
q.push(pRoot);
TreeNode* p=NULL;
int level=1;
while(!q.empty()){
int n=q.size();
vector<int> vec;
while(n--){
p=q.front();
q.pop();
if(level&1){
vec.push_back(p->val);
}else{
vec.insert(vec.begin(),p->val);
}
if(p->left)
q.push(p->left);
if(p->right)
q.push(p->right);
}
ans.push_back(vec);
level++;
}
return ans;
}
};
//方法2:分析之字形打印特点,利用两个栈和一个标记实现
//存在两份几乎相同的while()代码
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
if(pRoot==NULL) return res;
stack<TreeNode*> stk;
stack<TreeNode*> stk2;
stk.push(pRoot);
int mark=0; //0从左到右 1从右到左
TreeNode* p=NULL;
while(!stk.empty() || !stk2.empty()){
vector<int> vec;
if(mark==0){
while(!stk.empty()){
p=stk.top();
stk.pop();
vec.push_back(p->val);
if(p->left){
stk2.push(p->left);
}
if(p->right){
stk2.push(p->right);
}
}
mark=1;
}else{
while(!stk2.empty()){
p=stk2.top();
stk2.pop();
vec.push_back(p->val);
if(p->right){
stk.push(p->right);
}
if(p->left){
stk.push(p->left);
}
}
mark=0;
}
res.push_back(vec);
}
return res;
}
};
//方法3:利用栈数组和控制变量current、next精简代码
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
if(pRoot==NULL) return res;
stack<TreeNode*> stk[2];
int current=0,next=1;
stk[current].push(pRoot);
TreeNode* p=NULL;
while(!stk[0].empty() || !stk[1].empty()){
vector<int> vec;
while(!stk[current].empty()){
p=stk[current].top();
stk[current].pop();
vec.push_back(p->val);
if(current==0){
if(p->left){
stk[next].push(p->left);
}
if(p->right){
stk[next].push(p->right);
}
}else{
if(p->right){
stk[next].push(p->right);
}
if(p->left){
stk[next].push(p->left);
}
}
}
res.push_back(vec);
current=1-current;
next=1-next;
}
return res;
}
};