AVLTree-cpp

AVLTree-cpp - Attach to the left of previous...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
AVLTree.cpp #include"AVLTree.h" AVLTree::AVLTree() { root = NULL; } AVLTree::insert(KeyType key, ValueType val) { // Find node. If key exists overwrite value. AVLNode *current = root; AVLNode *previous = NULL; while(current != NULL) { previous = current; if(key == current->key) { // Found key, overwrite value current -> value = val; return TRUE; } else if(key > current->key) { // key is in the right child current = current->right; } else { // key is in the left child current = current->left; } } // At this point previous points to the parent where we have to insert the nwe node. // Create new node // pic3 AVLNode *n = new AVLNode(); assert(n! = NULL);//make suer there is memory n->key = key; n->value = val; n->height = 1; n->left = NULL; n->right = NULL; n->parent = previous; if(previous == NULL) { // TRee is empty root = n; // simplest case
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
return FALSE; } if(previous->key > key)
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: { // Attach to the left of previous previous->left = n; } else { // Attach to the right of previous previous->right = n; } // Adjust height of the nodes only update heights in the path from inserted node to root AVLNode *m = n->parent; while(m != NULL) // O(log n) { // Go up // Get max height of left and right children int maxheight = 0; if(m -> left != NULL) { maxheight = m->left->height; } if(m->right != NULL && maxheight < m->right->height) { maxheight = m->right->height; } m->height = 1 + maxheight; m = m->parent; } // At this point the node is in place and the heights are correct. However, this may not // be an AVL tree because the difference in heights of some of the children mayvbe greater // than one. we will "restructure" starting at the inserted node "n". restucture(n); }...
View Full Document

{[ snackBarMessage ]}

Page1 / 2

AVLTree-cpp - Attach to the left of previous...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online