StackTc 2018-01-30 13:48 采纳率: 90.9%
浏览 1022
已采纳

TreeMap排序源码分析有疑问

直接上代码

public V put(K key, V value) {//插入或设置元素,返回原始value值(如果插入返回null)  
        Entry<K,V> t = root;  
        if (t == null) {//根元素为空时直接建立根元素  
        // TBD:  
        // 5045147: (coll) Adding null to an empty TreeSet should  
        // throw NullPointerException  
        //  
        // compare(key, key); // type check  
            root = new Entry<K,V>(key, value, null);  
            size = 1;  
            modCount++;  
            return null;  
        }  
        int cmp;  
        Entry<K,V> parent;  
        // split comparator and comparable paths  
        Comparator<? super K> cpr = comparator;  
        if (cpr != null) {//存在比较器  
            do {//循环查找父元素  
                parent = t;//设置父元素  
                cmp = cpr.compare(key, t.key);  
                if (cmp < 0)  
                    t = t.left;//继续查找左边元素  
                else if (cmp > 0)  
                    t = t.right;//继续查找右边元素  
                else  
                    return t.setValue(value);//相等直接进行value设置  
            } while (t != null);  
        }  
        else {//不存在比较器,按compareTo方法查找  
            if (key == null)  
                throw new NullPointerException();  
            Comparable<? super K> k = (Comparable<? super K>) key;  
            do {  
                parent = t;  
                cmp = k.compareTo(t.key);  
                if (cmp < 0)  
                    t = t.left;  
                else if (cmp > 0)  
                    t = t.right;  
                else  
                    return t.setValue(value);  
            } while (t != null);  
        }  
        Entry<K,V> e = new Entry<K,V>(key, value, parent);  
        if (cmp < 0)  
            parent.left = e;  
        else  
            parent.right = e;  
        fixAfterInsertion(e);  
        size++;  
        modCount++;  
        return null;  
    }  

疑问点在于,

if (cmp < 0)
t = t.left;
else if (cmp > 0)
t = t.right;
else
return t.setValue(value);

上面这段代码的意思是,根据比较器想t移到原来节点的子节点。那么移动以后parent节点是原来的t,t变到了原来的子节点,那么下面这段代码又是什么意思呢。

if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);

让parent的左右节点成e(插入节点),那么岂不是跟t节点重复了?t阶段存在的意义到底是什么。

  • 写回答

4条回答 默认 最新

  • threenewbee 2018-01-30 16:58
    关注

    if (cmp < 0)
    parent.left = e;
    else
    parent.right = e;
    fixAfterInsertion(e);
    如果比较是小于,然后插入左边,否则插入右边
    t节点是原来的,e是插入的。先要搬动原来的节点,然后再插入e。
    最后fixAfterInsertion(e); 调整二叉树使平衡。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 Matlab问题解答有两个问题
  • ¥50 Oracle Kubernetes服务器集群主节点无法访问,工作节点可以访问
  • ¥15 LCD12864中文显示
  • ¥15 在使用CH341SER.EXE时不小心把所有驱动文件删除了怎么解决
  • ¥15 gsoap生成onvif框架
  • ¥15 有关sql server business intellige安装,包括SSDT、SSMS。
  • ¥15 stm32的can接口不能收发数据
  • ¥15 目标检测算法移植到arm开发板
  • ¥15 利用JD51设计温度报警系统
  • ¥15 快手联盟怎么快速的跑出建立模型