-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0102BinaryTreeLevelOrderTraversal.java
More file actions
34 lines (32 loc) · 1.04 KB
/
_0102BinaryTreeLevelOrderTraversal.java
File metadata and controls
34 lines (32 loc) · 1.04 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
package com.heatwave.leetcode.problems;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class _0102BinaryTreeLevelOrderTraversal {
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new LinkedList<>();
if (root == null) {
return ans;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
List<Integer> level = new LinkedList<>();
int n = queue.size();
while (n-- > 0) {
TreeNode node = queue.remove();
level.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
ans.add(level);
}
return ans;
}
}
}