AcWing 44. 分行从上往下打印二叉树
原题链接
中等
作者:
andream7
,
2020-12-25 17:12:23
,
所有人可见
,
阅读 290
/**
* 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;
q.push(root);
while(q.size()) {
int len = q.size();
vector<int> lev;
for (int i = 0; i < len; i++) {
auto t = q.front();
q.pop();
lev.push_back(t->val);
if (t->left) q.push(t->left);
if (t->right) q.push(t->right);
}
res.push_back(lev);
}
return res;
}
};