I don't really understand what your code is supposed to do. It doesn't seem to be storing the node anywhere. I would expect that constructBalancedTree
should be returning a node shouldn't it? Something like:
class BST {
private Node root;
BST(T[] array) {
root = constructBalancedTree(array, 0, array.length - 1);
}
private Node constructBalancedTree(T[] array, int i, int j) {
if(i > j) {
return null;
} else {
int mid = (i+j)/2;
Node node = new Node(array[mid]);
node.setLeft(constructBalancedTree(array, i, mid-1));
node.setRight(constructBalancedTree(array, mid+1, j));
return node;
}
}
}
In terms of printing the tree you have lots of options. You could add a toString
method that recursive prints child nodes; you could use a Visitor design pattern to visit all nodes; you could have a method that gets the values as a list or stream:
class Node<T> {
private Node left;
private Node right;
private T value;
public Stream<T> getValues() {
Stream.Builder<T> values = Stream.builder();
if (left != null)
left.getValues().forEach(values::accept);
values.accept(value);
if (right != null)
right.getValues().forEach(values::accept);
return values.build;
}
}
Then you can just print the values: System.out.println(root.getValues().collect(Collectors.joining(", "))
.