Ok so in my binary search tree I made a bunch of methods but I'm currently testing 2 of them. One of them inserts an item into the tree:
public void insert(String word) { //calls the insert method
root=insertItem(root, word);
}
protected TreeNode insertItem(TreeNode r, String word) { //inserts an item x into the tree
if(r==null){
r = new TreeNode(new WordRefs(word));
r.left = null;
r.right = null;
}
else if(word.compareTo(r.item.getWord()) < 0){
r.left = insertItem(r.left, word);
} else if (word.compareTo(r.item.getWord()) > 0){
r.left = insertItem(r.right, word);
}
return r;
}
The other one deletes an item:
public void delete(String word) { //calls the delete method
root = deleteItem(root, word);
}
protected TreeNode deleteItem(TreeNode r, String word) { //deletes an item x from the BST
if (r == null){
return r;
}
if(word.compareTo(r.item.getWord()) < 0){
r.left = deleteItem(r.left, word);
} else if (word.compareTo(r.item.getWord()) > 0){
r.right = deleteItem(r.right, word);
} else if(r.left != null && r.right != null){
return deleteItem(r, word);
}
return r;
}
And here is the code that tests these methods
public static void main(String args[]) { //the tests are in the main method
BSTRefBased t;
AbstractBinaryTree tt;
int i;
boolean result;
String message;
message = "Test 1: inserting 'word1' -- "; //tests the insert method first
t = new BSTRefBased();
try {
t.insert("word1");
result = t.getRootItem().getWord().equals("word1");
} catch (Exception e) {
result = false;
}
System.out.println(message + (result ? "passed" : "FAILED"));
message = "Test 2: inserting 'word1', 'word2', 'word3' -- ";
t = new BSTRefBased();
try {
t.insert("word1");
t.insert("word2");
t.insert("word3");
result = t.getRootItem().getWord().equals("word1");
tt = t.detachLeftSubtree();
result &= tt.getRootItem().getWord().equals("word2");
tt = t.detachRightSubtree();
result &= tt.getRootItem().getWord().equals("word3");
} catch (Exception e) {
result = false;
}
System.out.println(message + (result ? "passed" : "FAILED"));
message = "Test 3: deleting 'word1' -- "; //it then tests the delete method (note I keep getting failed for this one)
t = new BSTRefBased();
try {
t.delete("word1");
result = t.getRootItem().getWord().equals(null);
} catch (Exception e) {
result = false;
}
System.out.println(message + (result ? "passed" : "FAILED"));
message = "Test 4: deleting 'word2' 'word3' -- ";
t = new BSTRefBased();
try {
t.delete("word2");
t.delete("word3");
result = t.getRootItem().getWord().equals(null);
tt = t.detachLeftSubtree();
result &= tt.getRootItem().getWord().equals(null);
} catch (Exception e) {
result = false;
}
System.out.println(message + (result ? "passed" : "FAILED"));
}
For my output it says test 1 passed but test 2, 3, and 4 all failed. So why did test 2, 3, and 4 fail?
Aucun commentaire:
Enregistrer un commentaire