コーディングの宿題で少し問題があります。ツリーの 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;
}
助けてくれてありがとう
編集:コードを文字列でテストしていますが、ジェネリック型が使用されているため、問題にならないことを願っています。