题目描述
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
解:
两个栈
/*
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>> result;
if(!pRoot)
return result;
stack<TreeNode*> s[2];
int current = 0;
int next = 1;
s[current].push(pRoot);
vector<int> v;
while(!s[current].empty() || ! s[next].empty()){
TreeNode* pCur = s[current].top();
s[current].pop();
v.push_back(pCur->val);
if(current == 0){
if(pCur->left)
s[next].push(pCur->left);
if(pCur->right)
s[next].push(pCur->right);
}else{
if(pCur->right)
s[next].push(pCur->right);
if(pCur->left)
s[next].push(pCur->left);
}
if(s[current].empty()){
result.push_back(v);
v.clear();
current = 1 - current;
next = 1 - next;
}
}
return result;
}
};