AcWing 45. 之字形打印二叉树-deque好理解
原题链接
中等
作者:
溜溜球
,
2021-03-22 18:11:26
,
所有人可见
,
阅读 405
算法1
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 {};
vector<vector<int>> ans;
deque<TreeNode*> q;
q.push_back(root);
int cnt = 1;
while(!q.empty()){
int len = q.size();
vector<int> f;
while(len --){
if(cnt % 2 == 1){
auto cur = q.front(); q.pop_front();
f.push_back(cur->val);
if(cur->left) q.push_back(cur->left);
if(cur->right) q.push_back(cur->right);
} else{
auto cur = q.back(); q.pop_back();
f.push_back(cur->val);
if(cur->right) q.push_front(cur->right);
if(cur->left) q.push_front(cur->left);
}
}
cnt ++;
ans.push_back(f);
}
return ans;
}
};