-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLevel Order Traversal.java
More file actions
27 lines (27 loc) · 1.14 KB
/
Copy pathLevel Order Traversal.java
File metadata and controls
27 lines (27 loc) · 1.14 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
//Level order traversal in a binary tree
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if (root == null) return ans;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
//Null will partition the elements in the queue by their level
// If null occurs during traversal then there is complete traversal of the level.
queue.offer(null);
List<Integer> currentList = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
if (current == null) {
ans.add(currentList);
if (queue.isEmpty()) return ans;
queue.offer(null);
currentList = new ArrayList<>();
}
else {
currentList.add(current.val);
if (current.left != null) {
queue.offer(current.left);
}
if (current.right != null) {
queue.offer(current.right);
}
}