1
TreeMap (MyTreeMap)의 구현을 위해 노력 중이며 put 메서드에 많은 문제가 있습니다. 누군가가 내 코드를보고 잘못된 방향으로 올바른 방향으로 나를 가리킬 수 있기를 바랬습니다.TreeMap 구현 메서드를 입력하십시오.
public class MyTreeMap<K extends Comparable<? super K>,V> extends AbstractMap<K,V> {
K key;
V value;
int height;
MyTreeMap<K,V> left,right;
int size;
public V put(K key, V value) {
int compareValue = this.key.compareTo(key);
if(!this.containsKey(key)) {
if(this.key == null) {
this.key = key;
this.value = value;
}
if(this.isLeaf() || this.isEmpty()) {
if(this.key.compareTo(key) > 0)
this.left = new MyTreeMap<K,V>(key,value,null,null);
else
this.right = new MyTreeMap<K,V>(key,value,null,null);
if(left.height > right.height + 1 || right.height > left.height + 1)
restructure(this);
this.size++;
setHeight();
return null;
}
else {
if(compareValue > 0)
return this.left.put(key, value);
else
return this.right.put(key, value);
}
}
else {
if(compareValue == 0) {
V temp = this.value;
this.value = value;
return temp;
}
else if(compareValue < 0)
return this.right.put(key, value);
else
return this.left.put(key, value);
}
}
답장을 보내 주셔서 감사합니다. containsKey 대신 compareValue == 0을 사용하면 정말 도움이되었습니다. 호기심에서 널 키를 어떻게 허용하지 않습니까? – user1547050