二进制搜索树按顺序遍历新数组

时间:2015-03-16 14:43:07

标签: java recursion binary-search-tree

我已经完成了BST按顺序遍历,同时作为练习打印到控制台,但任务是将其添加到新列表中......

我尝试通过在方法外创建列表并递增值来以类似的方式执行此操作' x'同时添加到array [i]列表但我不断收到NullPointerException

任何人都可以帮我找出原因吗?

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;
}

由于

1 个答案:

答案 0 :(得分:5)

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

您实际上需要 初始化 数组

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