我试图为多态二叉搜索树编写size()方法。 即具有EmptyTree和NonEmptyTree类的BST,它们都实现了一个"树"接口。 EmptyTree用于表示空树或子树而不是null(如在常规BST中)
public interface Tree<K extends Comparable<K>, V> {
public int size();
public NonEmptyTree<K, V> add(K key, V value);
//bunch of other methods
}
我已经使EmptyTree和NonEmptyTree都从Tree接口实现了size()方法,如下所示:
public int size() { //in EmptyTree class
return 0;
}
public int size() { //in NonEmptyTree class
return 1 + left.size() + right.size();
}
但是,当我尝试在测试中运行它时:
Tree<Integer, String> treeThree = EmptyTree.getInstance(); //EmptyTree is a singleton class
treeThree = treeThree.add(3, "3");
treeThree = treeThree.add(2, "2");
treeThree = treeThree.add(1, "1");
treeThree = treeThree.add(4, "4");
assertEquals(4, treeThree.size());
它表示treeThree的大小是3,而不是4应该是。
虽然它适用于这些:
Tree<Integer, String> empty = EmptyTree.getInstance();
assertEquals(0, empty.size());
Tree<Integer, String> treeOne = EmptyTree.getInstance();
treeOne = treeOne.add(2, "2"); treeOne = treeOne.add(1, "1"); treeOne = treeOne.add(3, "3");
assertEquals(3, treeOne.size());
Tree<Integer, String> treeTwo = EmptyTree.getInstance();
treeTwo = treeTwo.add(3, "3"); treeTwo = treeTwo.add(2, "2");
assertEquals(2, treeTwo.size());
EmptyTree add方法:
public NonEmptyTree<K, V> add(K key, V value) {
return new NonEmptyTree(key, value);
}
NonEmptyTree添加方法:
public NonEmptyTree<K, V> add(K key, V value) {
if(this.key.compareTo(key) == 0) {
this.value = value;
return this;
}
else {
if(key.compareTo(this.key) < 0) {
if(this.left.lookup(key) == null) {
this.left = new NonEmptyTree<K,V>(key, value);
return this;
}
else
return this.left.add(key, value);
}
else if(key.compareTo(this.key) > 0) {
if(this.right.lookup(key) == null) {
this.right = new NonEmptyTree<K,V>(key, value);
return this;
}
else
return this.right.add(key, value);
}
}
return this;
}
EmptyTree查找:
public V lookup(K key) {
return null;
}
NonEmptyTree查找:
public V lookup(K key) {
if(key.compareTo(this.key) == 0)
return this.value;
else {
if(key.compareTo(this.key) < 0)
return this.left.lookup(key);
if(key.compareTo(this.key) > 0)
return this.right.lookup(key);
}
return null;
}
答案 0 :(得分:2)
正如j_random_hacker先生在评论中所说,您不需要在add方法中调用查找方法。这将替换包含EmptyTree的整个子树作为它的子项。 改变你的添加方法,
public NonEmptyTree<K, V> add(K key, V value) {
if(this.key.compareTo(key) == 0) {
this.value = value;
}
else {
if(key.compareTo(this.key) < 0) {
this.left = this.left.add(key, value);
}
else {
this.right = this.right.add(key, value);
}
}
return this;
}