-3
BST(T[] array) {
    constructBalancedTree(array, 0, array.length - 1);

}
void constructBalancedTree(T[] array, int i, int j) {
    if(i > j) {
        return;
    }

    int mid = (i+j)/2;
    Node node = new Node(array[mid]);

    constructBalancedTree(array, i, mid-1);
    constructBalancedTree(array, mid+1, j);
}

I'm trying to figure out how to print this out in the main. I have created:

BST<Integer> t1 = new BST<Integer>(new Integer[] {1, 5, 9, 12, 13, 15})

but when i try to print it out, it gives me a reference

ekta
  • 67
  • 10

2 Answers2

-1

You need to iterate through the array to print the elements in it. In Java an Array is an object so System.out.println(t1); in your case will print the reference to the object. Try

for(int i = 0; i < t1.length(); i++) {
    System.out.println(t1[i]);
 }
minaco77
  • 1
  • 1
  • 3
-1

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(", ")).

sprinter
  • 27,148
  • 6
  • 47
  • 78