-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinary Tree Level Order Traversal
39 lines (39 loc) · 1.07 KB
/
Binary Tree Level Order Traversal
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
/**
* 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 {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> levelOrder(TreeNode root) {
if(root == null) return new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
while(!q.isEmpty()){
int s = q.size();
List<Integer> temp = new ArrayList<>();
for(int i = 0; i<s; i++){
TreeNode cur = q.poll();
temp.add(cur.val);
if(cur.left != null){
q.add(cur.left);
}
if(cur.right != null){
q.add(cur.right);
}
}
res.add(temp);
}
return res;
}
}