题目描述
blablabla
样例
blablabla
算法1(BFS)
/**
* 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) {
queue<TreeNode*> q;
vector<vector<int>> res;
if (!root) return res;
q.push(root);
while (q.size()) {
res.push_back({});
int sz=q.size();
for (int i=0;i<sz;i++) {
auto cur=q.front();
q.pop();
res.back().push_back(cur->val);
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
}
return res;
}
};