converting BST to array

I’ve looked all over and can’t seem to find any help for this.. for a school project I have a BST tree and I have to put all the ints from the tree into an int array called BSTarray.
This is what I have so far:

public int [] toBSTArray() {
    int size = 20;
    int [] BSTarray = new int [size];
    for(int i = 0; i <size; i++) {
        makeArray(root);
        BSTarray[i] = root.getValue();
}

    return BSTarray;
}

//helper method called by toBSTArray
public void makeArray(BinarySearchTreeNode node) {
    if (node != null) {
        makeArray(node.getLeft());
        makeArray(node.getRight());
        // System.out.print(node.getValue() + " ");
    }
}

I thought this method was supposed to go through the tree and add in the values it finds into different indexes in the BSTarray, but all it’s doing is adding the same number into all the indexes in the array. Am I doing something wrong with the recursion?

Answer

Try this:

Integer[] values = extractValues(n).toArray(new Integer[] {});

with that method definition:

private static List<Integer> extractValues(Node n) {
    List<Integer> result = new ArrayList<>();
    if (n.getLeft() != null) {
        result.addAll(extractValues(n.getLeft()));
    }

    if (n.getRight() != null) {
        result.addAll(extractValues(n.getRight()));
    }

    result.add(n.getValue());

    return result;
}

I assumed a node structure that is similar to yours. Of course, the method doesn’t have to be static if you don’t use it in a static way.

This method might not be the most efficient due to the list conversion but you don’t have to bother with any array sizes. If you really need the function to return an array, just wrap it into another function or let the proposed function return an array (this would make it necessary to convert the list to an array before each return).

Concerning your code, you iterate over the ito fill the entire array (no matter where you know the size from) but you always set the value to the value of the root node. That’s why you always have the same value. Your makeArray function calls itself recursively but it doesn’t do anything (even if you add a sysout statement 😉 )

Update:

And for the constraint of using no lists, here is another version that uses only arrays:

int size = 20;
int[] results = new int[size];
extractValues(n, results, 0);

with the method definition:

private static int extractValues(Node n, int[] results, int index) {
    if (n.getLeft() != null) {
        index = extractValues(n.getLeft(), results, index);
    }

    if (n.getRight() != null) {
        index = extractValues(n.getRight(), results, index);
    }

    results[index] = n.getValue();

    return index + 1;
}

Note, that the result will be in results, then. The size has to be either assumed to be larger the number of nodes or it has to be counted by traversing the tree, before.