좋아, 전화 번호부에 BinarySearchTree가있는 DictionaryADT 인터페이스를 구현하고 있습니다. BST 추가 및 삭제를 제외하고 내 파일이 제대로 작동합니다. 중복 된 항목을 추가 할 수 없지만 트리가 중복되어 추가 할 수 없으며 그 이유는 알 수 없습니다. 마찬가지로 삭제할 때 내 삭제 된 항목이 테스트 파일에서 발견되므로 삭제가 전혀 작동하지 않는다고 생각합니다! 내 방법은 다음과 같습니다. 어떤 도움이라도 대단히 감사합니다.자바의 BinarySearchTree에서 메소드 추가 및 삭제
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);
}
수정 해 주셔서 감사합니다. 또한 삭제 방법에서 실수를 잡았습니까? 그것은 작동하지 않는 것 같습니다. – user1798812
'insert'에 의해 추가 된 중복과 관련이 있을지도 모릅니다. '삽입 '을 수정하여 시작하십시오. – SomeWittyUsername
글쎄, 그건 그 일을하기 전에 작동하고 있던 전화 번호부에 null 포인터 예외를 준 때문에 작동하지 않는 것 같습니다. 내 추가 방법에서 볼 수있는 것은, 실제로 아무 것도 삽입하지 않고 확인하지 않고 크기를 늘리는 것이므로 아무 것도 삽입해도 결과를 정의하는 else 조건을 사용해야합니다. 아닙니다. 이제 어떻게해야합니까,이 논리를 코드화하는 방법을 생각할 수 없습니다 ... 제발 도와주세요. – user1798812