-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBTLevelSearch.java
More file actions
40 lines (39 loc) · 1.17 KB
/
BTLevelSearch.java
File metadata and controls
40 lines (39 loc) · 1.17 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
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BTLevelSearch {
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
if(root == null) return ans;
LinkedList<TreeNode> q = new LinkedList<TreeNode>();
LinkedList<Integer> qidx = new LinkedList<Integer>();
q.offer(root);
qidx.offer(0);
while(!q.isEmpty()){
TreeNode now = q.poll();
int nowIdx = qidx.poll();
if(ans.size() ==nowIdx){
ArrayList<Integer> tmp = new ArrayList<Integer>();
tmp.add(now.val);
ans.add(tmp);
}else{
ans.get(ans.size()- 1).add(now.val);
}
if(now.left != null){
q.offer(now.left);
qidx.offer(nowIdx +1);
}
if(now.right != null){
q.offer(now.right);
qidx.offer(nowIdx +1);
}
}
return ans;
}
}