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'。 –