-
Notifications
You must be signed in to change notification settings - Fork 19.9k
/
Copy pathLevelOrderTraversal.java
54 lines (46 loc) · 1.52 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
47
48
49
50
51
52
53
54
package com.thealgorithms.datastructures.trees;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public final class LevelOrderTraversal {
private LevelOrderTraversal() {
}
public 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<>();
for (int i = 0; i < nodesOnLevel; i++) {
BinaryTree.Node tempNode = q.poll();
level.add(tempNode.data);
if (tempNode.left != null) {
q.add(tempNode.left);
}
if (tempNode.right != null) {
q.add(tempNode.right);
}
}
result.add(level);
}
return result;
}
/* Print nodes at the given level */
public static void printGivenLevel(BinaryTree.Node root, int level) {
if (root == null) {
System.out.println("Root node must not be null! Exiting.");
return;
}
if (level == 1) {
System.out.print(root.data + " ");
} else if (level > 1) {
printGivenLevel(root.left, level - 1);
printGivenLevel(root.right, level - 1);
}
}
}