forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLevelOrderTraversal.java
46 lines (39 loc) · 1.4 KB
/
LevelOrderTraversal.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
39
40
41
42
43
44
45
46
package com.thealgorithms.datastructures.trees;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/* Class to print Level Order Traversal */
public class LevelOrderTraversal {
/* Given a binary tree. Print its nodes in level order
using array for implementing queue */
static List<List<Integer>> traverse(BinaryTree.Node root) {
if (root == null) {
return List.of();
}
List<List<Integer>> result = new ArrayList<>();
Queue<BinaryTree.Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
int nodesOnLevel = q.size();
List<Integer> level = new LinkedList<>();
/* poll() removes the present head.
For more information on poll() visit
http://www.tutorialspoint.com/java/util/linkedlist_poll.htm */
for (int i = 0; i < nodesOnLevel; i++) {
BinaryTree.Node tempNode = q.poll();
level.add(tempNode.data);
/*Enqueue left child */
if (tempNode.left != null) {
q.add(tempNode.left);
}
/*Enqueue right child */
if (tempNode.right != null) {
q.add(tempNode.right);
}
}
result.add(level);
}
return result;
}
}