-
Notifications
You must be signed in to change notification settings - Fork 19.4k
/
TreeTestUtils.java
46 lines (43 loc) · 1.39 KB
/
TreeTestUtils.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 com.thealgorithms.datastructures.trees.BinaryTree.Node;
import java.util.LinkedList;
import java.util.Queue;
public final class TreeTestUtils {
private TreeTestUtils() {
}
/**
* Creates a binary tree with given values
*
* @param values: Level order representation of tree
* @return Root of a binary tree
*/
public static Node createTree(final Integer[] values) {
if (values == null || values.length == 0 || values[0] == null) {
throw new IllegalArgumentException("Values array should not be empty or null.");
}
final Node root = new Node(values[0]);
final Queue<Node> queue = new LinkedList<>();
queue.add(root);
int end = 1;
while (end < values.length) {
final Node node = queue.remove();
if (values[end] == null) {
node.left = null;
} else {
node.left = new Node(values[end]);
queue.add(node.left);
}
end++;
if (end < values.length) {
if (values[end] == null) {
node.right = null;
} else {
node.right = new Node(values[end]);
queue.add(node.right);
}
}
end++;
}
return root;
}
}