简体   繁体   中英

Put method of a TreeMap implementation

I'm working on an implementation of TreeMap(called MyTreeMap) and I'm having a lot of trouble with the put method. I was hoping someone could look at my code and point me in the right direction as to where things start to go wrong.

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);
        }
}

I think your logic is a bit inside-out, and as a result is a lot more complicated than it needs to be: the top level if should probably be looking at the compareValue , not doing the containsKey check.

Logic should be:

  • if compareValue==0 then this means you have found the right key, so just update the value and return
  • otherwise check the left or right branch as appropriate (depending on sign of compareValue):
    • if the branch is null, then turn it into a new TreeMap branch containing your key and value (you are now done)
    • otherwise (branch is not null), call put recursively on this branch. If you like you can do rebalancing logic after this call.

PS I suggest not allowing null keys in a TreeMap, it will make your life simpler, and will avoid the need to do null checks on keys

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM