简体   繁体   English

TreeMap实现的put方法

[英]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. 我正在开发TreeMap(称为MyTreeMap)的实现,但是put方法遇到了很多麻烦。 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. 我认为您的逻辑有点由内而外,结果比所需的要复杂得多:顶层if应该查看compareValue ,而不是执行containsKey检查。

Logic should be: 逻辑应为:

  • if compareValue==0 then this means you have found the right key, so just update the value and return 如果compareValue==0则意味着您找到了正确的键,因此只需更新值并返回
  • otherwise check the left or right branch as appropriate (depending on sign of compareValue): 否则,请根据需要检查向左或向右分支(取决于compareValue的符号):
    • if the branch is null, then turn it into a new TreeMap branch containing your key and value (you are now done) 如果分支为null,则将其转换为包含您的键和值的新TreeMap分支(现已完成)
    • otherwise (branch is not null), call put recursively on this branch. 否则(分支不为null),请对该分支进行递归调用。 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 PS:我建议在TreeMap中不允许使用空键,这会使您的生活更简单,并且避免对键进行空值检查

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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