-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathM_102_Binary_Tree_Level_Order_Traversal.java
More file actions
43 lines (43 loc) · 1.23 KB
/
M_102_Binary_Tree_Level_Order_Traversal.java
File metadata and controls
43 lines (43 loc) · 1.23 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
/**
* 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<>();
List<List<Integer>> ll=new ArrayList<>();
if(root==null)
return ll;
List<Integer> l=new ArrayList<>();
l.add(root.val);
ll.add(l);
q.add(root);
while(q.isEmpty()!=true)
{
List<Integer> l2=new ArrayList<>();
int qlen=q.size();
for(int x=0;x<qlen;x++)
{
TreeNode temp=q.poll();
if(temp.left!=null)
{
l2.add(temp.left.val);
q.add(temp.left);
}
if(temp.right!=null)
{
l2.add(temp.right.val);
q.add(temp.right);
}
}
if(l2.size()!=0)
ll.add(l2);
}
return ll;
}
}