forked from hongtaocai/code_interview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlevel.java
More file actions
executable file
·43 lines (37 loc) · 1.28 KB
/
level.java
File metadata and controls
executable file
·43 lines (37 loc) · 1.28 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
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
ArrayList<ArrayList<Integer>> arr = new ArrayList<ArrayList<Integer>>();
if(root==null) return arr;
Queue<TreeNode> qc = new LinkedList<TreeNode>();
Queue<TreeNode> qn = new LinkedList<TreeNode>();
ArrayList<Integer> al = new ArrayList<Integer>();
qn.offer(root);
TreeNode c;
while(true){
if(qc.isEmpty() && qn.isEmpty()){
if(al.size()!=0){
arr.add(new ArrayList<Integer>(al));
al.clear();
}
break;
}
if(qc.isEmpty()){
Queue<TreeNode> tmp = qc;
qc = qn;
qn = tmp;
if(al.size()!=0){
arr.add(new ArrayList<Integer>(al));
al.clear();
}
}else{
c = qc.poll();
if(c.left!=null) qn.offer(c.left);
if(c.right!=null) qn.offer(c.right);
al.add(c.val);
}
}
return arr;
}
}