0
新しいノードが置かれるたびにrootが新しい値を取得するのはなぜですか?私は、ルート変数は、バイナリツリーの最初の要素への参照になるはずです。なぜSedgwickはBSTで毎回ルートに新しいノードを割り当てるのですか?
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;
}
}
最初は 'root == null'を最初に(/'x.left == null' /' x.right == null'をツリー内で深く)扱うだけです。他のすべてのケースでは、割り当てはノーオペレーションです。 –