0
vvIはIntegerのみで動作するBSTを持っていましたが、ジェネリックスに変更しようとするまではすべて正常でした。ジェネリックスBSTヌルポインタ
public class Tree<T extends Comparable<T>> {
Node root = null;
private class Node {
T key;
Node left, right, parent = null;
Node(T key) {
this.key = key;
}
}
public void insert(T key) {
if (root == null)
root = new Node(key);
else {
Node actual = root;
Node parent = null;
while(actual != null) {
parent = actual;
actual = (actual.key.compareTo(key) > 0) ? actual.left : actual.right;
}
if (parent.key.compareTo(key) > 0) {
parent.left = new Node(key);
parent.left.parent = parent;
}
if (parent.key.compareTo(key) <= 0) {
parent.right = new Node(key);
parent.right.parent = parent;
}
}
}
/********************** end BSTInsert *******************************/
public Node search(T key) {
Node actual = root;
while (actual != null && actual.key != key) {
actual = (actual.key.compareTo(key) > 0) ? actual.left : actual.right;
}
if (actual == null) {
System.out.println("dont exist");
return null;
}
return actual;
}
public void inOrder(Node node) {
if (node != null) {
inOrder(node.left);
System.out.print(node.key + ", ");
inOrder(node.right);
}
}
}
これはコードの一部です。ファンクション検索には、ヌルポインタだけでなく、残りの関数にも問題があります(リストにはありません)。ファンクション検索では、ヌルポインタが与えられ、その理由はわかりません。関数insertとinOrderが正常に動作するようです。
変更前のコードが整数で正常に機能していたため、この問題はJavaのジェネリックの理解にあります。
ありがとうございます。
@edit あなたはそうです。 BSTツリーは正常です。問題は、このコードにあるすべての
public class TreeTest {
public static void main(String args[]){
Tree<String> tree = new Tree<String>();
tree.insert("a");
tree.insert("b");
tree.insert("c");
tree.inOrder(tree.root);
tree.search("b"); //everything is fine
Scanner read = new Scanner(System.in);
String txt;
txt = read.nextLine(); //write b
tree.search(txt); //there is no b in tree
}
}
Stacktraceしてください。 – SaurabhJinturkar