java - 关于二叉查找树的put方法
大家讲道理
大家讲道理 2017-04-18 10:05:44
0
1
620

看二叉查找树的时候看到put方法:

 public void put(Key key, Value val) {
        if (key == null) throw new NullPointerException("first argument to put() is null");
        if (val == null) {
            delete(key);
            return;
        }
        root = put(root, key, val);
        assert check();
    }

    private Node put(Node x, Key key, Value val) {
        //if key存在于以x为结点的子树中则更新它的值
        //then 将以key和val为键值的新结点插入到该子树中
        if (x == null) return new Node(key, val, 1);
        int cmp = key.compareTo(x.key);
        //比它小往左边走
        if      (cmp < 0) x.left  = put(x.left,  key, val);
        //不然往右边走
        else if (cmp > 0) x.right = put(x.right, key, val);
        //找到了就赋新的值
        else              x.val   = val;
        x.size = 1 + size(x.left) + size(x.right);//为什么要+1???
        return x;
    }

为什么要x.size = 1 + size(x.left) + size(x.right);??进入这里的条件是如果该结已存在就赋予新的值吧?那么仅仅是更新一个值为什么要增加1个size呢?

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
刘奇

There is a problem with the comment. For binary search trees, put actually means insert.

  1. If cmp < 0 || cmp > 0, then there will be one more node in the left subtree or right subtree, then the size will be increased by 1

  2. If cmp==0, it is equivalent to adding a duplicate node. Under normal circumstances, will not append a duplicate node to the tree, but add 1 to the current node.size

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!