previous | start | next

Insertion in a Binary Search Tree

Recall insertion (without rebalancing) into a Binary Search Tree. We assume the BST has a private member root whose value is null if the BST is empty:

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

private Node insert(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, v, t.left);
  } else if ( k.compareTo(t.key) > 0 ) {
     t.right = put(k, v, t.right);
  }
  return t;
}
   


previous | start | next