题目描述:
请实现一个函数按照之字形顺序从上向下打印二叉树。
即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
数据范围
树中节点的数量 [0,1000]。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]
8
/ \
12 2
/ \
6 4
输出:[[8], [2, 12], [6, 4]]
/**
* 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>> res;
queue<TreeNode *> q;
if(root) q.push(root);
int flag = 1;
while(q.size()) {
int len = q.size();
vector<int> path;
while(len --) {
auto t = q.front();
path.push_back(t->val);
q.pop();
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
if (flag == -1) reverse(path.begin(), path.end());
res.push_back(path);
flag *= -1;
}
return res;
}
};