Single rotation

Hide text Hide pseudo-code

The AVL-tree below is out of balance after the last insertion (in the model solution you can see the state before and after the insertion). Balance the tree by making a rotation.

// p is unbalanced, f is p's father
if (f->left == p) {
  if (height(p.left) > height(p.right)) {
    f->left = p->left;  // single rotation right
    p->left = f->left->right;
    f->left->right = p;
  } else { // height(p.left) < height(p.right)
    f->left = p->right; // single rotation left
    p->right = f->left->left;
    f->left->left = p;
  }
} else { // f->right == p
  if (height(p.left) < height(p.right)) {
    f->right = p->right; // single rotation left
    p->right = f->right->left;
    f->right->left = p;
  } else { // height(p.left) > height(p.right)
    f->right = p->left;  // single rotation right
    p->left = f->right->right;
    f->right->right = p;  
  }
}


  Created Wed Jun 20 16:00:43 EEST 2007 - Powered by SVG-hut