0
我在编写一些作业时遇到了一些麻烦。我应该编写一个通用二进制搜索树实用程序,其中包括一个用于返回Tree的postOrder traversion的ArrayList的方法。我的代码编译,但它会抛出一个NullPointerException除了空的树。我的错误在哪里?通用BinarySearchTree中的PostOrder输出(Java)
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'。 –