目录
1.剑指Offer
面试题32:之字形打印二叉树
题目描述:请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路:使用两个栈层次遍历,奇数行和偶数行入栈顺序不同。
代码:
技巧:栈数组和变量的使用
stack<TreeNode*> levels[2];
int current=0;
int next=1;
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
if(pRoot==nullptr) return res;
stack<TreeNode*> levels[2];
int current=0;
int next=1;
levels[current].push(pRoot);
vector<int> temp;
while(!levels[0].empty()||!levels[1].empty()){
TreeNode* p=levels[current].top();
levels[current].pop();
temp.push_back(p->val);
if(current==0){
if(p->left){
levels[next].push(p->left);
}
if(p->right){
levels[next].push(p->right);
}
}
else{
if(p->right){
levels[next].push(p->right);
}
if(p->left){
levels[next].push(p->left);
}
}
if(levels[current].empty()){
current=1-current;
next=1-next;
res.push_back(temp);
temp.clear();
}
}
return res;
}
};
面试题32:把二叉树打印成多行
题目描述:从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
思路:使用队列
代码:
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
if(pRoot==nullptr) return res;
queue<TreeNode*> q;
q.push(pRoot);
while(!q.empty()){
int n=q.size();
vector<int> temp;
while(n--){
TreeNode* p=q.front();
temp.push_back(p->val);
q.pop();
if(p->left){
q.push(p->left);
}
if(p->right){
q.push(p->right);
}
}
res.push_back(temp);
}
return res;
}
};