题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
-----------------------------------------------------------------------------------------------------------------
用一个队列和一个栈实现,做判断 偶数进队列,基数进栈
/*
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> >bp;
deque<TreeNode*> res;
stack<TreeNode*> fin;
if (!pRoot)return bp;
res.push_back(pRoot);
int loo = 0;
while (!res.empty() || !fin.empty())
{
int j =0,p = res.size(), q = fin.size();
vector<int> cm;
if (loo % 2 ==0)
{
while (j++ < p)
{
cm.push_back(res.front()->val);
if (res.front()->left)fin.push(res.front()->left);
if (res.front()->right)fin.push(res.front()->right);
res.pop_front();
}
}
else if (loo % 2 == 1)
{
while (j++ < q)
{
cm.push_back(fin.top()->val);
if (fin.top()->right)res.push_front(fin.top()->right);
if (fin.top()->left)res.push_front(fin.top()->left);
fin.pop();
}
}
loo++;
bp.push_back(cm);
}
return bp;
}
};