madcrazydrumma
madcrazydrumma

Reputation: 1897

Binary Search Tree In-Order Traversal to a new array

I've done a BST in-order traversal whilst printing out to the console as an exercise, but the task was to add it into a new list...

I tried doing it a similar way by creating the list outside the method and incrementing a value 'x' whilst adding to the array[i] list but I keep getting a NullPointerException

Can anyone help me figure out why?

int[] bstArray;
int x = 0;

public int[] returnInOrderTraversal(BSTNode node) {
    if(node == null) return bstArray;

    if(node.getLeftChild() != null) {
        returnInOrderTraversal(node.getLeftChild());
    }

    bstArray[x] = node.getValue();
    x++;

    if(node.getRightChild() != null) {
        returnInOrderTraversal(node.getRightChild());
    }

    return bstArray;
}

Thanks

Upvotes: 1

Views: 92

Answers (1)

Neeraj Jain
Neeraj Jain

Reputation: 7730

int[] bstArray;  <-------- This line does not create the Array

You actually need to initialize the array

int[] bstArray=new bstArray[someLength]; <------- like this
then use 
bstArray[x] = node.getValue();

Upvotes: 5

Related Questions