previous | start | next

The put Method

Insertion into a BST is very much like the get method.

public void put(Key k, Value v)

That is, move through the tree as if you were searching for k. When a null reference is reached, attach a new node containing k and v.

A recursive version again uses a pair of methods. The public method return type is void, but the private method returns a reference to the root Node of the modified subtree into which the data was inserted:

  public void put(Key k, Value v)
  {
    root = put(k, v, root);
  }

  private Node put(Key k, Value v, Node t)
  {
    if ( t == null )
        t = new Node(k,v);
    else if ( k.compareTo(t.key) < 0 ) {
        t.left = insert(x, t.left);
    }
    else if ( k.compareTo(t.key) > 0 ) {
        t.right = insert(x, t.right);
    }
    else {
        // k is already in the tree;
        // update k's value
        t.val = v;
    }
    return t;
  }



previous | start | next