AcWing 45. 之字形打印二叉树
原题链接
中等
作者:
沙漠绿洲
,
2020-09-28 19:18:45
,
所有人可见
,
阅读 314
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) {
if(!root) return {};
queue<TreeNode*> q;
q.push(root);
vector<vector<int>> ret;
int cnt = 0;
while(!q.empty()){
int len = q.size(), n = len;
vector<int> ans(n);
while(len --){
auto t = q.front();
q.pop();
if(cnt & 1) ans[len] = t->val;
else ans[n - len - 1] = t->val;
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
ret.emplace_back(move(ans));
++ cnt;
}
return ret;
}
};