-
Notifications
You must be signed in to change notification settings - Fork 16
/
BinaryTreeLevelOrderTraversal.java
38 lines (34 loc) · 1.11 KB
/
BinaryTreeLevelOrderTraversal.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
// https://leetcode.com/problems/binary-tree-level-order-traversal
// T: O(n)
// S: O(n)
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class BinaryTreeLevelOrderTraversal {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return List.of();
}
final Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
queue.add(null);
final List<List<Integer>> result = new ArrayList<>();
List<Integer> level = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
if (current == null) {
result.add(level);
if (!queue.isEmpty()) {
queue.add(null);
level = new ArrayList<>();
}
} else {
level.add(current.val);
if (current.left != null) queue.add(current.left);
if (current.right != null) queue.add(current.right);
}
}
return result;
}
}