2016-05-18 9 views
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 
     } 
    } 
+3

Stacktraceしてください。 – SaurabhJinturkar

答えて

0

まず、これは再帰を使用して理解する方法が容易です。

第2に、あなたが私に何かを見せなければ、あなたのエラーを見ることはできません。

私は自分自身完璧に働いているBSTのアルゴリズムで見つける作った:

protected Node<E> find(E element, Node<E> node) { 
     if (node == null) { 
      return null; 
     } 
     if (node.getElement() == element) { 
      return node; 
     } 
     if (node.getElement().compareTo(element) > 0) { 
      return find(element, node.getLeft()); 
     } else { 
      return find(element, node.getRight()); 
     } 
    } 

あなたは私に多くの情報を与えた場合、多分私はサービスのより多くのことができます。