mad*_*mma 1 java recursion binary-search-tree
我已经完成了BST按顺序遍历,同时作为练习打印到控制台,但任务是将其添加到新列表中......
我尝试通过在方法外部创建列表并在添加到数组[i]列表时递增值"x"以类似方式执行此操作但我不断获得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;
}
Run Code Online (Sandbox Code Playgroud)
谢谢
int[] bstArray; <-------- This line does not create the Array
Run Code Online (Sandbox Code Playgroud)
您实际上需要初始化数组
int[] bstArray=new bstArray[someLength]; <------- like this
then use
bstArray[x] = node.getValue();
Run Code Online (Sandbox Code Playgroud)