-
Notifications
You must be signed in to change notification settings - Fork 0
/
p158.java
43 lines (42 loc) · 1.14 KB
/
p158.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
// https://leetcode.com/problems/binary-tree-level-order-traversal/]
/**
* Definition for a binary tree node.
* public 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 Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> mainls=new ArrayList<>();
Queue<TreeNode> q=new LinkedList<>();
q.add(root);
if(root==null){
return mainls;
}
while(!q.isEmpty()){
int s=q.size();
List<Integer> ls=new ArrayList<>();
for(int i=0;i<s;i++){
TreeNode curr=q.remove();
ls.add(curr.val);
if(curr.left!=null){
q.add(curr.left);
}
if(curr.right!=null){
q.add(curr.right);
}
}
mainls.add(ls);
}
return mainls;
}
}