previous | start | next

Implementation of the put 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 = put(k, t.left); // (***)
    }
    else if ( k.compareTo(t.key) > 0 ) {
        t.right = put(k, t.right);
    }
    else {
        // k is already in the tree;
        // update k's value
        t.val = v;
    }
    return t;
  }

(***) Before the recursive call we are going down the tree to insert (k,v) in the left subtree, then after the return from the recursive call, we are returning back up the tree and (re)attach the modified left subtree as t's left child.



previous | start | next