-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path102. Binary Tree Level Order Traversal.java
86 lines (68 loc) · 2.16 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
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
77
78
79
80
81
82
83
84
85
86
import java.util.*;
// * Definition for a binary tree node.
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class TreeNodeAndDepth {
TreeNode node;
int depth;
TreeNodeAndDepth(TreeNode node, int depth){
this.depth = depth;
this.node = node;
}
}
class Solution {
List<List<Integer>> result = new ArrayList<>();
HashMap<Integer,List<Integer>> map = new HashMap<>();
private void breathFirstSearch(TreeNode root){
if(root == null){
return;
}
Queue<TreeNodeAndDepth> queue = new LinkedList<>();
List<Integer> rootLevel = new ArrayList<>();
rootLevel.add(root.val);
map.put(0,rootLevel);
queue.add(new TreeNodeAndDepth(root,0));
while(queue.size()>0){
TreeNodeAndDepth cur = queue.poll();
if(cur.node.left != null){
queue.add(new TreeNodeAndDepth(cur.node.left,cur.depth+1));
List<Integer> curLevel;
if(map.containsKey(cur.depth+1)){
curLevel = map.get(cur.depth + 1);
}
else{
curLevel = new ArrayList<>();
}
curLevel.add(cur.node.left.val);
map.put(cur.depth+1,curLevel);
}
if(cur.node.right != null){
queue.add(new TreeNodeAndDepth(cur.node.right,cur.depth+1));
List<Integer> curLevel;
if(map.containsKey(cur.depth+1)){
curLevel = map.get(cur.depth + 1);
}
else{
curLevel = new ArrayList<>();
}
curLevel.add(cur.node.right.val);
map.put(cur.depth+1,curLevel);
}
}
}
public List<List<Integer>> levelOrder(TreeNode root) {
breathFirstSearch(root);
result.addAll(map.values());
return result;
}
}