-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolutionJZ60.java
More file actions
76 lines (68 loc) · 2.19 KB
/
SolutionJZ60.java
File metadata and controls
76 lines (68 loc) · 2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.company;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class SolutionJZ60 {
/*
BFS的模板为:
1.如果不需要确定当前遍历到了哪一层,模板如下:
void 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
}
2.如果需要确定遍历到哪一层,模板如下:
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
}
*/
/*
使用队列进行层序遍历
*/
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
TreeNode head=pRoot;
Queue<TreeNode> queue=new LinkedList<>();
ArrayList<ArrayList<Integer>> result=new ArrayList<>(); //保存结果
if(head!=null)
queue.add(head);
while (!queue.isEmpty()){
int sz= queue.size(); //记录栈的深度:每一行元素个数
ArrayList<Integer> temp=new ArrayList<>(); //保存每一行结果
while(sz!=0){
TreeNode node=queue.peek();
queue.poll();
temp.add(node.val);
if(node.left!=null)
queue.add(node.left);
if(node.right!=null)
queue.add(node.right);
sz--;
}
result.add(temp);
}
return result;
}
}