forked from JsonChao/Awesome-Algorithm-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Solution102.java
65 lines (51 loc) · 1.66 KB
/
Solution102.java
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
package queue_problem;
import com.sun.tools.javac.util.Pair;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* 树:层序遍历。102、107、103、199
* O(n)
* O(n)
* 二叉树的层次遍历:层次遍历和广度优先遍历其实是很像的,
* 在循环中使用队列就好。唯一的不同是每一层单独一个list,
* 因此我们就需要想想办法让每层分隔开,我使用的办法就是
* 每次塞进去一个root作为分隔。
*/
public class Solution102 {
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public List<List<Integer>> levelOrder(TreeNode root) {
ArrayList<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
// 使用队列先进先出的特性
LinkedList<Pair<TreeNode, Integer>> queue = new LinkedList<>();
queue.add(new Pair<>(root, 0));
while (!queue.isEmpty()) {
Pair<TreeNode, Integer> pair = queue.removeFirst();
TreeNode node = pair.fst;
int level = pair.snd;
if (level == res.size()) {
res.add(new ArrayList<>());
}
assert level < res.size();
res.get(level).add(node.val);
if (node.left != null) {
queue.addLast(new Pair<>(node.left, level + 1));
}
if (node.right != null) {
queue.addLast(new Pair<>(node.right, level + 1));
}
}
return res;
}
}