-
Notifications
You must be signed in to change notification settings - Fork 1
/
leetcode102.java
45 lines (40 loc) · 1.12 KB
/
leetcode102.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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list=new ArrayList<List<Integer>>();
if(root==null)
return list;
Queue<TreeNode> que=new LinkedList<TreeNode>();
que.offer(root);
que.offer(null);
List<Integer> listOfTreeNode = new ArrayList<Integer>();
while(que.size()!=1){
TreeNode p=que.poll();
if(p==null){
que.offer(null);
list.add(listOfTreeNode);
listOfTreeNode = new ArrayList<Integer>();
}
else{
listOfTreeNode.add(p.val);
if(p.left!=null){
que.offer(p.left);
}
if(p.right!=null){
que.offer(p.right);
}
}
}
if(listOfTreeNode.size()!=0)
list.add(listOfTreeNode);
return list;
}
}