previous | start | next

Insertion in an AVL Tree

An AVL tree is a binary search tree with a balance condtition

The insertion for an AVL tree uses the same code as for any biinary search tree (above), but must add code to keep the AVL tree balanced and to compute changes in heights of nodes:

public void insert(E x)
{
   root = insert(x, root);
}

private Node insert(E x, Node t)
{
  if ( t == null ) {
     t = new Node(x);
  } else if ( x.compareTo(t.data) < 0 ) {
     t.left = insert(x, t.left);
     // If t is unbalanced call rotate method(s) to restore the balance
  } else if ( x.compareTo(t.data) > 0 ) {
     t.right = insert(x, t.right);
     // If t is unbalanced call rotate method(s) to restore the balance
  }
  // Recompute the height of t if height is member of Node
  return t;
}
   


previous | start | next