这是我的代码。我被困在删除部分。 insert和get方法都很好。我想保存旧树,以便我可以很快将节点链接在一起。
private BinaryTree<K, V> left, right;
public BinaryTree(K key, V value) {
// Leaf node constructor
this.key = key;
this.value = value;
}
public V put(K key, V value) {
if (this.key.equals(key)) {
// Replacing the value at the current node
V ret = this.value;
this.value = value;
return ret;
}
int comp = this.key.compareTo(key);
if (comp < 0) {
// this.key < key
// Put the key we are inserting to the right
// of the current key
if (right == null) {
// We have to create a node to the right
// (Leaf node)
right = new BinaryTree<K, V>(key, value);
return null; // Per interface
}
return right.put(key, value);
} else {
// We don't support keys where equals and compareTo
// disagree with each other.
assert(comp != 0);
// At this point, we know that comp > 0
// Therefore, this.key > key
// Put the key we are inserting to the left of current
if (left == null) {
// We have to create a node to the left
// (Leaf node)
left = new BinaryTree<K, V>(key, value);
return null; // Per interface
}
return left.put(key, value);
// Exercise: You could write a tiny little private method
// to implement this redundant code in one place.
}
}
public V get(K key) {
int comp = this.key.compareTo(key);
if (comp < 0) {
// this.key < key
// Recurse to the right
if (right == null) {
// Not in the tree
return null;
}
return right.get(key);
} else if (comp > 0) {
// this.key > key
// Recurse to the left
if (left == null) {
// Not in the tree
return null;
}
return left.get(key);
} else {
assert(this.key.equals(key));
return value;
}
}
public boolean containsKey(K key) {
// Note: Doesn't work with null values!
return get(key) != null;
}
public BinaryTree<K, V> delete(K key) {
BinaryTree<K,V> tmp,childL,childR,OldTree;
int comp=this.key.compareTo(key);
if(comp<0){
//this.key<Key goes right
if(this.right==null){
throw new UnsupportedOperationException("Nothing you can delete here");
}
else{
return this.right.delete(key);
}
}
if(comp>0){
if(this.left==null){
throw new UnsupportedOperationException("Nothing you can delte here");
}
else{
return this.left.delete(key);
}
}
if(this.key.equals(key)){
}
{
}
//}
// IMPLEMENT THIS FOR YOUR ASSIGNMENT!
// Remove key from the tree, if it exists.
// Throw UnsupportedOperationException if key isn't in the tree.
// Return the new root node if we did delete the key.
// (The new root node may be the same as the old one.)
// If you deleted the last node in the tree, it will return null.
return null;
}}
一些细节发布在常见的,我的代码是否是逻辑错误?