题目描述:给定一颗二叉树,从左到右从上到下打印二叉树。要求是要按层换行。
方法:层次遍历打印二叉树,用队列实现。本题是上一篇的变形,区别就是这个需要考虑到层数。
首先复习一下模板:
如果不需要确定当前遍历到了哪一层,模板如下:
void bfs() {
vis[] = 0;
queue<int> pq(start_val);
while (!pq.empty()) {
int cur = pq.front(); pq.pop();
for (遍历cur所有的相邻节点nex) {
if (nex节点有效 && vis[nex]==0){
vis[nex] = 1;
pq.push(nex)
}
}
}
}
如果需要确定遍历到哪一层,模板如下;
```cpp
void bfs() {
int level = 0;
vis[] = {0}; // or set
queue<int> pq(original_val);
while (!pq.empty()) {
int sz = pq.size();
while (sz--) {
int cur = pq.front(); pq.pop();
for (遍历cur所有的相邻节点nex) {
if (nex节点有效 && vis[nex] == 0) {
vis[nex] = 1;
pq.push(nex)
}
} // end for
} // end inner while
level++;
} // end outer while
}
本题代码:
class Solution {
public:
vector<vector<int> > Print(TreeNode* pRoot) {
vector<vector<int>> res;
if(!pRoot) return res;
queue<TreeNode*> help;
help.push(pRoot);//根节点入队列
while(!help.empty()){
int sz=help.size();
vector<int> ans;
while(sz--){
TreeNode * node=help.front();//先保存队列头节点
help.pop();//队首元素出队列
ans.push_back(node->val);//出队列的元素压入vector
if(node->left) help.push(node->left);//将出队列元素的非空左右子节点入队列
if(node->right) help.push(node->right);
}
res.push_back(ans);//将一个容器压入到另一个容器,实现多行打印
}
return res;
}
};