繁体   English   中英

TreeMap实现的put方法

[英]Put method of a TreeMap implementation

我正在开发TreeMap(称为MyTreeMap)的实现,但是put方法遇到了很多麻烦。 我希望有人可以查看我的代码,并向我指出发生错误的正确方向。

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

我认为您的逻辑有点由内而外,结果比所需的要复杂得多:顶层if应该查看compareValue ,而不是执行containsKey检查。

逻辑应为:

  • 如果compareValue==0则意味着您找到了正确的键,因此只需更新值并返回
  • 否则,请根据需要检查向左或向右分支(取决于compareValue的符号):
    • 如果分支为null,则将其转换为包含您的键和值的新TreeMap分支(现已完成)
    • 否则(分支不为null),请对该分支进行递归调用。 如果愿意,您可以在此调用之后进行逻辑重新平衡。

PS:我建议在TreeMap中不允许使用空键,这会使您的生活更简单,并且避免对键进行空值检查

暂无
暂无

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

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