题目描述:
从上到下按层打印二叉树,同一层结点从左至右输出。
//每一层输出一行。(需要分行打印)
1.不分行打印
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> res;//返回的类型是vector,所以定义一个结果res
if(!root) return res;
//非空
queue<TreeNode*> q;
q.push(root);
//bfs 广度优先遍历
while(q.size())
{
auto t = q.front();
q.pop();
res.push_back(t -> val);
if(t -> left) q.push(t -> left);
if(t -> right) q.push(t -> right);
}
return res;
}
};
2.分行打印
/*
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> > res;
if(!pRoot) return res;
queue<TreeNode*> q;
q.push(pRoot);//先将根节点和一个空指针压入队列中
q.push(nullptr); //nullptr空指针 表示分行
vector<int> layer; //实例化层layer
while(q.size())
{
auto t = q.front();//取队首
q.pop();
//读到nullptr表示分行 把layer push到 res
if(!t)//如果t是空指针
{
if(layer.empty()) break;
res.push_back(layer);//将layer push到res中
layer.clear();
q.push(nullptr);//在节点的下一行左右都在队列中时,压入一个空指针,分行
continue;
}
layer.push_back(t -> val);//实现分层
if(t -> left) q.push(t -> left);
if(t -> right) q.push(t -> right);
}
return res;
}
};
分行过程:
q:
8 n --> n 12 2 --> 12 2 n --> 2 n --> n 6 --> 6 n --> n 4 --> 4 n --> n --> n (break)