forked from DengWangBao/Leetcode-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinaryTreeLevelOrderTraversal.java
49 lines (37 loc) · 1.16 KB
/
BinaryTreeLevelOrderTraversal.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
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class BinaryTreeLevelOrderTraversal {
// 耗时2ms
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new LinkedList<List<Integer>>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
Queue<TreeNode> next = new LinkedList<TreeNode>();
queue.add(root);
List<Integer> cur = null;
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (cur == null) {
cur = new LinkedList<Integer>();
result.add(cur);
}
cur.add(node.val);
if (node.left != null) {
next.add(node.left);
}
if (node.right != null) {
next.add(node.right);
}
if (queue.isEmpty()) {
Queue<TreeNode> temp = queue;
queue = next;
next = temp;
cur = null; // 注意这里要置空
}
}
return result;
}
}