わかりましたので、PhoneBook の BinarySearchTree を使用して DictionaryADT インターフェイスを実装しています。私のファイルは、BST の追加と削除を除いて正常に動作しています。重複したエントリを追加することは許可されていませんが、ツリーに重複が追加されており、その理由がわかりません。削除でも同様に、削除したエントリがテスト ファイルで見つかったので、削除がまったく機能しないと思います。これが私の方法です:どんな助けも本当に感謝しています。
public boolean add(K key, V value) {
if (root == null)
root = new Node<K, V>(key, value);
else
insert(key, value, root, null, false);
currentSize++;
modCounter++;
return true;
}
private void insert(K k, V v, Node<K, V> n, Node<K, V> parent, boolean wasLeft)
{
if (n == null) {
if (wasLeft)
parent.leftChild = new Node<K, V>(k, v);
else
parent.rightChild = new Node<K, V>(k, v);
}
else if (((Comparable<K>) k).compareTo((K) n.key) < 0)
insert(k, v, n.leftChild, n, true);
else
insert(k, v, n.rightChild, n, false);
}
ここに私の削除があります:
public boolean delete(K key){
if (!this.contains(key)) {
return false;
}
Node<K, V> node = find(key, root, 0);
Node<K,V> parent = remove(node, root);
root=parent;
currentSize--;
modCounter++;
return true;
}
private Node<K,V> remove( Node<K,V> node_to_delete, Node<K,V> start_node )
{
if( start_node == null )
return start_node;
if(((Comparable<K>)node_to_delete.key).compareTo( start_node.key ) < 0 )
start_node.leftChild = remove( node_to_delete, start_node.leftChild );
else if(((Comparable<K>)node_to_delete.key).compareTo( start_node.key ) > 0 )
start_node.rightChild = remove( node_to_delete, start_node.rightChild );
else if( start_node.leftChild != null && start_node.rightChild != null )
{
start_node.key = findMin( start_node.rightChild ).key;
start_node.rightChild = remove( start_node, start_node.rightChild );
}
else
start_node = ( start_node.leftChild != null ) ? start_node.leftChild : start_node.rightChild;
return start_node;
}
private Node<K,V> findMin( Node<K,V> t )
{
if( t == null )
return null;
else if( t.leftChild == null )
return t;
return findMin( t.leftChild );
}