标签:code == public ack layer 思路 temp 打印二叉树 二叉树
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
代码如下:
/*
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>> ans;
if(pRoot==nullptr)
return ans;
stack<TreeNode*> s1;
stack<TreeNode*> s2;
s1.push(pRoot);
int curLayer = 1; //当前是第几层
while(!s1.empty() || !s2.empty()){
if(curLayer%2!=0){
vector<int> temp; //存储当前层的节点
while(!s1.empty()){
TreeNode* node = s1.top();
s1.pop();
if(node!=nullptr){
temp.push_back(node->val);
s2.push(node->left);
s2.push(node->right);
}
}
if(!temp.empty()){
//curLayer++;
ans.push_back(temp);
}
}
else{
vector<int> temp;
while(!s2.empty()){
TreeNode* node = s2.top();
s2.pop();
if(node!=nullptr){
temp.push_back(node->val);
s1.push(node->right);
s1.push(node->left);
}
}
if(!temp.empty()){
//curLayer++;
ans.push_back(temp);
}
}
curLayer++;
}
return ans;
}
};
【剑指Offer-举例让抽象问题具体化】面试题32.2:之字形打印二叉树
标签:code == public ack layer 思路 temp 打印二叉树 二叉树
原文地址:https://www.cnblogs.com/flix/p/12632690.html