最近在牛客上刷到一道题目,是遍历二叉树,是按照从左到右的顺序,也即bfs,最后输出一个二维数组,里面记录了每一层的元素。具体题目如下:
下面给出C++的解题方法
/*
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* pRoot) {
vector<vector<int>> ret;
if(!pRoot) return ret; //如果为空,直接返回空数组
queue<TreeNode *> q;
q.push(pRoot); //将根节点放进去
while(!q.empty())
{
vector<int> ans; /