题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
这道题还是二叉树的层序遍历思想,在每一层将数据存入另一个栈中,其实也可以用队列实现
/*
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 == nullptr) return res;
//用两个栈,一个存奇数层,一个存偶数层
stack<TreeNode*> stackL;
stack<TreeNode*> stackR;
TreeNode* popNode;
//用tmp暂存每一层的数据
vector<int> tmp;
tmp.push_back(pRoot->val);
res.push_back(tmp);
tmp.clear();
stackL.push(pRoot);
while(!stackL.empty() || !stackR.empty())
{
//处理奇数层
while(!stackL.empty())
{
popNode = stackL.top();
stackL.pop();
//因为偶数层需要逆序打印,所以这一层先存入节点的右孩子
if(popNode->right)
{
stackR.push(popNode->right);
tmp.push_back(popNode->right->val);
}
if(popNode->left)
{
stackR.push(popNode->left);
tmp.push_back(popNode->left->val);
}
}
if(!tmp.empty())
{
res.push_back(tmp);
tmp.clear();
}
//处理偶数层
while(!stackR.empty())
{
popNode = stackR.top();
stackR.pop();
//奇数层需要正序打印,所以存入左孩子
if(popNode->left)
{
stackL.push(popNode->left);
tmp.push_back(popNode->left->val);
}
if(popNode->right)
{
stackL.push(popNode->right);
tmp.push_back(popNode->right->val);
}
}
if(!tmp.empty())
{
res.push_back(tmp);
tmp.clear();
}
}
return res;
}
};