-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlevel_order_using_queue.java
More file actions
47 lines (41 loc) · 1.1 KB
/
Copy pathlevel_order_using_queue.java
File metadata and controls
47 lines (41 loc) · 1.1 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> q = new LinkedList<TreeNode>();
List<List<Integer>> r = new ArrayList<List<Integer>>();
if(root ==null)
return r;
q.add(root);
int s =1;
ArrayList<Integer> t = new ArrayList<Integer>();
while(!q.isEmpty()){
if(s==0)
{
// System.out.println("t");
System.out.println(t);
ArrayList<Integer> o = new ArrayList<Integer>(t);
r.add(o);
t.clear();
s=q.size();
}
TreeNode te = q.poll();
t.add(te.val);
if(te.left != null)
q.add(te.left);
if(te.right != null)
q.add(te.right);
--s;
}
ArrayList<Integer> o = new ArrayList<Integer>(t);
r.add(o);
return r;
}
}