-
Notifications
You must be signed in to change notification settings - Fork 176
/
BinaryTree.java
45 lines (40 loc) · 1.6 KB
/
BinaryTree.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
import java.util.*;
public class App {
static final class BinaryTree {
public final String value;
public final BinaryTree left;
public final BinaryTree right;
public BinaryTree(String v, BinaryTree l, BinaryTree r) {
value = v;
left = l;
right = r; // BUGFIX: not 'l'... with better names, this kind of error is less likely to happen!
}
public static BinaryTree fromList(List<String> list) {
// BUGFIX: Base case for the recursion
if (list.size() == 0) {
return null;
}
int mid = list.size() / 2;
// BUGFIX: Fixed the slicing bounds; note that the upper bound to subList is exclusive, as you can tell from its documentation
return new BinaryTree(list.get(mid), fromList(list.subList(0, mid)), fromList(list.subList(mid+1, list.size())));
}
public List<String> toList() {
var result = new ArrayList<String>();
if (left != null) {
result.addAll(left.toList());
}
result.add(value);
if (right != null) {
result.addAll(right.toList());
}
return result;
}
}
public static void main(String[] args) {
var list = List.of("ABC", "DEF", "GHI", "JKL", "MNO", "PQR", "STU");
var tree = BinaryTree.fromList(list);
var newList = tree.toList();
System.out.println("List before: " + String.join(", ", list));
System.out.println("List after: " + String.join(", ", newList));
}
}