题目描述
思路分析
二叉树+bfs
这个分行打印和不分行打印的区别是:
a
n
s
和
p
a
t
h
数
组
以
及
队
列
中
n
u
l
l
p
t
r
的
标
记
作
用
ans和path数组以及队列中nullptr的标记作用
ans和path数组以及队列中nullptr的标记作用
代码实现
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
*/
class Solution {
public:
vector<vector<int> > Print(TreeNode* root) {
vector<vector<int>> res;
if(!root) return res;
queue<TreeNode*> q;
q.push(root);
q.push(nullptr);
vector<int> path;
while(q.size()){
auto t=q.front();
q.pop();
if(!t){
if(!path.size()) break;
res.push_back(path);
path.clear();
q.push(nullptr);
continue;
}
path.push_back(t->val);
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
return res;
}
};