cs251-week7 tree implementation

cs251-week7 tree implementation - prev = n; // save...

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

View Full Document Right Arrow Icon
TREE IMPLENMENTATION Tree.h typedef struct TreeNode{ int key;// we ignore it for now int value; // assume key is an int struct TreeNode *left; struct TreeNode *right; }TreeNode; class Tree{ TreeNode *root; public: Tree(); bool add()int key,int value); bool lookup(int key, int value); bool remove(int key); } Tree.cpp Tree::Tree(){ root = NULL; } TreeNode *n = root; if(keykey){ n = n->left; }else{ n = n->right; } } //Two options if(n==NULL){ //the key was not found return false; } //the key was found value = n->value; return true; } bool Tree::add(int key, int value){
Background image of page 1

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

View Full DocumentRight Arrow Icon
//we need to find if the key is already there. TreeNode *n = root; TreeNode *prev = NULL;
Background image of page 2
Background image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: prev = n; // save programs value if(keykey){ n = n->left; }else{ n = n->right; } } if(n!=NULL){ //key exsists, replace value. n -> value = value; return true; } // key does not exsist n = new TreeNode; n->key = key; n->value = value; n->left = NULL; n->right = NULL; //check if tree was empty if(prev == NULL){ //the tree is empty root = n; return false; } // the tree is not empty if(keykey){ prev -> left = n; }else{ prev -> right = n; } return false; }- the add function does not guarantee that the tree will be balanced- We are going to see AVL trees that perform rebalancing after every insertion or removal if necessary....
View Full Document

This note was uploaded on 02/04/2012 for the course CS 251 taught by Professor Staff during the Fall '08 term at Purdue University-West Lafayette.

Page1 / 3

cs251-week7 tree implementation - prev = n; // save...

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

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