-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path102_binary_tree_level_order_traversal.java
More file actions
39 lines (36 loc) · 1.09 KB
/
102_binary_tree_level_order_traversal.java
File metadata and controls
39 lines (36 loc) · 1.09 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
/**
* 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) {
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
if (root == null) {
return res;
}
while (! queue.isEmpty()) {
List<Integer> levelRes = new ArrayList<>();
int levelSize = queue.size();
for (int i = 0; i < levelSize; i++) {
TreeNode currentTree = queue.poll();
if (currentTree == null) {
continue;
}
levelRes.add(currentTree.val);
if (currentTree.left != null)
queue.add(currentTree.left);
if (currentTree.right != null)
queue.add(currentTree.right);
}
res.add(levelRes);
}
return res;
}
}