previous | start | next

Recursive put

The difference between the recursive implementation of size and that of put, is that the private recursive method needs to return a reference to the modified subtree. This return Node is needed since new keys are inserted where a null link was. This null link needs to be reset to reference the Node returned by the recursive call.

The implementation:

public void put(int x)
{
  root = put(root, x);
}

private Node put(Node t, int x)
{
  if (t == null) {
    return new Node(x);
  }
  if (x < t.key) {
     t.left = put(t.left, x);
  } else if (x > t.key) {
     t.right = put(t.right, x);
  }
  return t;
}


previous | start | next