-
Notifications
You must be signed in to change notification settings - Fork 0
/
102.Binary_Tree_Level_Order_Traversal.java
46 lines (43 loc) · 1.33 KB
/
102.Binary_Tree_Level_Order_Traversal.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
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<> ();
if (root != null) {
queue.add(root);
}
while (queue.size() > 0) {
List<Integer> level = new ArrayList<>();
final int num = queue.size();
for (int i=0; i<num; i++) {
TreeNode node = queue.remove();
level.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
res.add(level);
}
return res;
}
}
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
rec(root, 1, res);
return res;
}
private void rec(TreeNode root, int level, List<List<Integer>> traversal) {
if (root == null) {
return;
}
if (level > traversal.size()) {
traversal.add(new ArrayList<>());
}
traversal.get(level-1).add(root.val);
rec(root.left, level+1, traversal);
rec(root.right, level+1, traversal);
}
}