题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
思路
- 栈的思想,安排两个栈,S1压入奇数行,S2压入偶数行,利用count来计算当前是在奇数行是偶数行,若是奇数行,则S1栈顶弹出,S2先压入栈顶的右,再压入栈顶的左,直至S1为空;若是偶数行则相反,S2栈顶弹出,先压左再压右。完成之后count++,记得需要判断res_p是否为空,若为空则说明已经到底
- 队列的思想,按照层序遍历的思路,若为偶数层则反向输出,奇数层则正向输出
代码
方法一:
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
vector<int> res_p;
if(pRoot == NULL)
return res;
stack<TreeNode*> S1_tree;
stack<TreeNode*> S2_tree;
S1_tree.push(pRoot);
res_p.push_back(pRoot->val);
res.push_back(res_p);
res_p.clear();
int count = 0;
while(S1_tree.size()>0 || S2_tree.size()>0)
{
if(count%2 == 0)
{
while(S1_tree.size() > 0)
{
TreeNode* current = S1_tree.top();
S1_tree.pop();
if(current->right)
{
S2_tree.push(current->right);
res_p.push_back(current->right->val);
}
if(current->left)
{
S2_tree.push(current->left);
res_p.push_back(current->left->val);
}
}
if(res_p.size()>0)
{
res.push_back(res_p);
res_p.clear();
}
count++;
}
else
{
while(S2_tree.size() > 0)
{
TreeNode* current = S2_tree.top();
S2_tree.pop();
if(current->left)
{
S1_tree.push(current->left);
res_p.push_back(current->left->val);
}
if(current->right)
{
S1_tree.push(current->right);
res_p.push_back(current->right->val);
}
}
if(res_p.size()>0)
{
res.push_back(res_p);
res_p.clear();
}
count++;
}
}
return res;
}
};
方法二:
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int> > res;
vector<int> res_p;
if(pRoot == NULL)
return res;
queue<TreeNode*> q_Tree;
q_Tree.push(pRoot);
res_p.push_back(pRoot->val);
res.push_back(res_p);
res_p.clear();
int count = 1;
while(q_Tree.size()>0)
{
int number = q_Tree.size();
while(number > 0)
{
TreeNode* current = q_Tree.front();
q_Tree.pop();
if(current->left)
{
q_Tree.push(current->left);
res_p.push_back(current->left->val);
}
if(current->right)
{
q_Tree.push(current->right);
res_p.push_back(current->right->val);
}
number--;
}
if(count%2 == 0 && res_p.size()>0)
{
res.push_back(res_p);
res_p.clear();
}
else if(count%2 == 1 && res_p.size()>0)
{
reverse(res_p.begin(),res_p.end());
res.push_back(res_p);
res_p.clear();
}
count++;
}
return res;
}
};