Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/sharepoint/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么Sedgwick每次在BST中都为root分配一个新节点?_Java_Algorithm_Binary Search Tree - Fatal编程技术网

Java 为什么Sedgwick每次在BST中都为root分配一个新节点?

Java 为什么Sedgwick每次在BST中都为root分配一个新节点?,java,algorithm,binary-search-tree,Java,Algorithm,Binary Search Tree,我不明白为什么每次放置一个新节点时root都会接受新值?我想根变量应该是对二叉树中第一个元素的引用 public class BST<Key extends Comparable<Key>, Value> { private Node root; // root of BST private class Node { private Key key; // sorted

我不明白为什么每次放置一个新节点时root都会接受新值?我想根变量应该是对二叉树中第一个元素的引用

public class BST<Key extends Comparable<Key>, Value> {
        private Node root;             // root of BST

        private class Node {
            private Key key;           // sorted by key
            private Value val;         // associated data
            private Node left, right;  // left and right subtrees
            private int size;          // number of nodes in subtree

            public Node(Key key, Value val, int size) {
                this.key = key;
                this.val = val;
                this.size = size;
            }
        }

        public void put(Key key, Value val) {
            root = put(root, key, val); //?!!
        }

        private Node put(Node x, Key key, Value 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);
            return x;
        }
}
公共类BST{
私有节点根;//BST的根
私有类节点{
私钥;//按密钥排序
私有值val;//关联的数据
私有节点左、右;//左、右子树
private int size;//子树中的节点数
公共节点(键、值val、整数大小){
this.key=key;
this.val=val;
这个。大小=大小;
}
}
公共作废put(键、值val){
root=put(root,key,val);/?!!
}
专用节点put(节点x、密钥、值val){
如果(x==null)返回新节点(key,val,1);
int cmp=键。比较(x.key);
如果(cmp<0)x.left=put(x.left,key,val);
否则,如果(cmp>0)x.right=put(x.right,key,val);
else x.val=val;
x、 尺寸=1+尺寸(x.左)+尺寸(x.右);
返回x;
}
}

root
实际上并不每次都接受新值。递归助手函数
put()
沿着树向下运行,直到到达死胡同,在这种情况下,它会创建一个新节点并将其返回到上次访问的节点

    if (x == null) return new Node(key, val, 1);
将其指定为

    if (cmp < 0) x.left = put(x.left, key, val);
    else if (cmp > 0) x.right = put(x.right, key, val);
如果树完全为空(如果
root
null
),则helper函数将立即创建一个新节点并返回该节点


一个关键观察结果:


作为第一个参数传递给helper函数的任何内容都会原封不动地返回,除非它是
null
,在这种情况下,将创建并返回一个新节点。

只需处理
root==null
的初始情况(/
x.left==null
/
x.right==null
在树的更深处)。在所有其他情况下,赋值都是不可操作的。
    root = put(root, key, val);