【发布时间】:2023-04-10 08:58:02
【问题描述】:
我在编写一些编码作业时遇到了一些麻烦。我应该编写一个通用二进制搜索树实用程序,包括一个返回树的 postOrder 遍历的 ArrayList 的方法。我的代码可以编译,但它会为除空树之外的所有树抛出 NullPointerException。我的错在哪里?
public ArrayList<T> postOrder(BinarySearchTree<T> tree) {
if (tree == null) {
return null;
} else {
ArrayList<T> post = new ArrayList<T>();
post.addAll(postOrder(tree.left));
post.addAll(postOrder(tree.right));
post.add(tree.thing);
return post;
}
}
BinarySearchTree 类是:
public class BinarySearchTree<T> {
/**
* The key by which the thing is refered to. Must be unique.
*/
public int key;
/**
* The thing itself.
*/
public T thing;
/**
* The left sub-tree
*/
public BinarySearchTree<T> left;
/**
* The right sub-tree
*/
public BinarySearchTree<T> right;
Biny
/**
* Create a new binary search tree without children.
* @param key the key by which the thing is refered to
* @param thing the new thing
*/
public BinarySearchTree(int key, T thing)
{
this.key = key;
this.thing = thing;
this.left = null;
this.right = null;
}
/**
* Create a new binary search tree
* @param key the key by which the thing is refered to
* @param thing the thing which is managed by the new binary search tree
* @param left the left sub-tree of the new binary search tree
* @param right the right sub-tree of the new binary search tree
*/
public BinarySearchTree(int key, T thing, BinarySearchTree<T> left, BinarySearchTree<T> right)
{
this.key = key;
this.thing = thing;
this.left = left;
this.right = right;
}
感谢您的帮助
编辑:我正在使用字符串测试我的代码,但由于使用了泛型类型,因此希望这无关紧要。
【问题讨论】:
-
哪一行给你NPE?
-
当您下降到递归结束时,在叶节点处,
postOrder()将为该节点的每个子节点返回null,对吗?当您将其传递给post.addAll()时,您认为会发生什么? -
当参数为
null时,考虑返回一个空的List而不是null。 -
行:post.addAll(postOrder(tree.left));
-
我认为它只会向 ArrayList 中添加任何内容,但这似乎确实值得尝试
标签: java generics binary-search-tree postorder