题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解答
层序遍历
1 | ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { |
官方题解
链接:https://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288?answerType=1&f=discussion
来源:牛客网
方法:队列
层次遍历打印二叉树,用队列实现。
有一句话,我觉得说的特别好:做题=解法+模板,意思就是说,对于一道题目,首先明白正确的解法已经解决该问题70%,剩下的就直接套模板。
所以BFS
的模板为:
如果不需要确定当前遍历到了哪一层,模板如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14void bfs() {
vis[] = {0}; // or set
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)
}
} // end for
} // end while
}
上述是伪代码,不仅可用于二叉树,可针对所有用BFS解题。
如果需要确定遍历到哪一层,模板如下;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20void 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
}
所以此题可直接套用模板,代码如下:
1 | class Solution { |
时间复杂度:O(N)
空间复杂度:O(1), vecotr<vecotr<int>>
是必须要开的,不算在额外空间里