AcWing 44. 分行从上往下打印二叉树
原题链接
中等
作者:
adamXu
,
2020-09-27 00:09:58
,
所有人可见
,
阅读 346
/**
* 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);
q.push(nullptr);
vector<int> cur;
while(q.size()){
auto t = q.front();
q.pop();
if(t){
cur.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
else{
if(q.size()) q.push(nullptr);
res.push_back(cur);
cur.clear();
}
}
return res;
}
};