简体   繁体   中英

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM