请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
/*
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>> t;
queue<TreeNode*> que; // 申请一个双向队列
deque<int> stk;
if(pRoot==NULL) return t;
que.push(pRoot);
int next = 0;
int current = 1;
int times = 1;
while(!que.empty()) {
vector<int> node;
while(current != 0 && !que.empty()){ //对当前层进行存储,并统计下一层的个数
TreeNode* top = que.front();
stk.push_back(top->val); //存入队列中
current--;
que.pop();
if(top->left!=NULL) {
que.push(top->left);
next++;
}
if(top->right!=NULL) {
que.push(top->right);
next++;
}
}
while(!stk.empty()) {
if(times % 2 == 0) { // 偶数从右到左输出
node.push_back(stk.back());
stk.pop_back();
} else {
node.push_back(stk.front()); //奇数从左到右输出
stk.pop_front();
}
}
times++;
t.push_back(node);
current = next;
next = 0;
}
return t;
}
};