AcWing 44. 分行从上往下打印二叉树
原题链接
中等
作者:
自说i
,
2024-01-28 18:13:03
,
所有人可见
,
阅读 33
/**
* 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>> arr;
vector<int> res;int cnt=0;
if(root==NULL) return arr;
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int width=q.size();
arr.push_back({});
for(int i=0;i<width;i++)
{
auto f=q.front();
q.pop();
arr[cnt].push_back(f->val);
if(f->left) q.push(f->left);
if(f->right) q.push(f->right);
}
cnt++;
}
return arr;
}
};