AcWing 44. 分行从上往下打印二叉树
原题链接
中等
作者:
Akihio
,
2021-05-07 20:54:11
,
所有人可见
,
阅读 229
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> >res;
if(!root)return res;
queue<TreeNode*>q,child;
vector<int>line;
q.push(root);
while(q.size()){
auto t=q.front();
line.push_back(t->val);
//printf("%d",t->val);
if(t->left){
child.push(t->left);
}
if(t->right){
child.push(t->right);
}
q.pop();
if(q.empty()){
while(child.size()){
//cout<<endl;
auto m=child.front();
q.push(m);
child.pop();
}
res.push_back(line);
line.clear();
}
}
return res;
}
};