AcWing 44. 分行从上往下打印二叉树
原题链接
中等
作者:
沙漠绿洲
,
2020-09-06 21:34:25
,
所有人可见
,
阅读 299
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;
while(!q.empty()){
int len = q.size();
vector<int> ans;
while(len --){
auto t = q.front();
q.pop();
ans.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
ret.emplace_back(ans);
}
return ret;
}
};