previous | start | next

Insertion in an AVL (with balancing code)

 Node * insert(const Key& k, const Value& v, Node *rt) {
    if (rt == NULL) {
      rt = new Node(k,v);
    } else if (k < rt->key) {
      rt->left = insert(k, v, rt->left);
      if ((height(rt->left) - height(rt->right)) > 1) {
        // balance 
             if (k < rt->left->key) {
          rt = rotateRight(rt);
        } else {
          rt ->left = rotateLeft(rt->left);
          rt = rotateRight(rt);
        }
      

      }
    } else if (k > rt->key) {
      rt->right = insert(k, v, rt->right);
      if ((height(rt->right) - height(rt->left)) > 1) {
        // balance
             if( k > rt->right->key) {
          rt = rotateLeft(rt);
        } else {
          rt->right = rotateRight(rt->right);
          rt = rotateLeft(rt);
        }
      
      }
    }
    rt->ht = max(height(rt->left), height(rt->right)) + 1;
    return rt;
  }


previous | start | next