【发布时间】:2020-05-12 13:04:19
【问题描述】:
我想将我的二叉搜索树转换为数组(按顺序遍历)。
要做到这一点,我有 3 种方法。
问题:方法 1 System.out.print() 调用中的 java.lang.NullPointerException。但是成功返回 4 个元素(2 个为 null,因此出现此错误,但为什么?!)
类(1个主)方法1(调用方法)
public void top() {
array[] unsortedList = this.bookList.returnBSTAsArray(6); // 6 is the number of nodes in tree
for (Book book: unsortedList) {
System.out.println("--> Title: " + book.title());
}
类(2)方法2
// traverse BST in order and return an array of books
public Book[] returnBSTAsArray(int totalLength) {
Book[] list = new Book[totalLength];
int index = 0;
storeInOrder(this.root, list, index); // root is node accessible to this class
return list;
}
类 (2) 方法 3 - 有趣的按顺序遍历的方法
private Book[] storeInOrder(Node root, Book[] array, int index) {
if (root == null)
return null;
storeInOrder(root.leftChild, array, index);
array[index++] = root.movie;
storeInOrder(root.rightChild, array, index);
return array;
}
【问题讨论】:
-
能把BST的代码放上来
-
另外,您要按插入顺序检索到 BST 吗?
标签: java arrays binary-search-tree binary-search inorder