题目描述
请实现一个函数按照之字形顺序从上向下打印二叉树。
即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]
8
/ \
12 2
/ \
6 4
输出:[[8], [2, 12], [6, 4]]
C++ 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> printFromTopToBottom(TreeNode* root) {
vector<vector<int>> V;
if(!root) return V;
queue<TreeNode*> q;
q.push(root);
int flag = 0;
while (!q.empty()) {
vector<int> v;
queue<TreeNode*> p;
while (!q.empty()) {
TreeNode* t = q.front();
q.pop();
if (t->left) p.push(t->left);
if (t->right) p.push(t->right);
v.push_back(t->val);
}
while (!p.empty()) {
q.push(p.front());
p.pop();
}
if (flag % 2 == 1) {
reverse(v.begin(),v.end());
}
V.push_back(v);
flag++;
}
return V;
}
};