-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeLevelOrderTraversal_102.java
More file actions
63 lines (55 loc) · 1.73 KB
/
BinaryTreeLevelOrderTraversal_102.java
File metadata and controls
63 lines (55 loc) · 1.73 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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> lists = new ArrayList<>();
if (root == null) return lists;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root); q.offer(null); // the marker of the end of a level
List<Integer> list = new ArrayList<>();
while (!q.isEmpty()) {
TreeNode tn = q.poll();
if (tn == null) {
lists.add(list);
if (q.isEmpty()) break;
list = new ArrayList<>();
q.offer(null);
}else{
list.add(tn.val);
if(tn.left != null) q.offer(tn.left);
if(tn.right != null) q.offer(tn.right);
}
}
return lists;
}
}
/**
* Not push null, use the queue size instead
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()) {
int length = q.size();
List<Integer> list = new ArrayList<>();
res.add(list);
for(int i=0; i<length; i++) {
TreeNode node = q.poll();
list.add(node.val);
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
}
return res;
}
}