题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
/*
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) {
}
};
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
if(pRoot == NULL)
return res;
stack<TreeNode *> s1; //奇数层:从左向右
stack<TreeNode *> s2; //偶数层:从右向左
TreeNode *popNode;
vector<int> tmp;
tmp.push_back(pRoot->val);
res.push_back(tmp);
tmp.clear();
s1.push(pRoot);
while( !s1.empty() || !s2.empty())
{
while(!s1.empty())
{
popNode = s1.top();
s1.pop();
if(popNode->right)
{
s2.push(popNode->right);
tmp.push_back(popNode->right->val);
}
if(popNode->left)
{
s2.push(popNode->left);
tmp.push_back(popNode->left->val);
}
}
if(!tmp.empty())
{
res.push_back(tmp);
tmp.clear();
}
while(!s2.empty())
{
popNode = s2.top();
s2.pop();
if(popNode->left)
{
s1.push(popNode->left);
tmp.push_back(popNode->left->val);
}
if(popNode->right)
{
s1.push(popNode->right);
tmp.push_back(popNode->right->val);
}
}
if(!tmp.empty())
{
res.push_back(tmp);
tmp.clear();
}
}
return res;
}
};