BST implementation: ususally pointer-based.
Tree node struct:
data pointer;
left child pointer;
right child pointer;
optional key field;
optional parent pointer;
BST operations:
lookup(Key k)
ptr = root;
while (ptr != 0 && ptr->key != k) {
if (ptr->key > k)
ptr = ptr->left;
else
ptr = ptr->right;
}
if (ptr == 0)
throw exception of not found
else
return ptr->data;
insert(Key k, Data d)
if (root == 0) {
root = new Node;
store d in the root node;
} else {
left = true;
parent = 0;
ptr = root;
while (ptr != 0 && ptr->key != k) {
parent = ptr;
if (ptr->key > k) {
ptr = ptr->left;
left = true;
} else {
ptr = ptr->right;
left = false;
}
}
if (ptr != 0)
throw exception of duplicate key
else {
if (left) {
parent->left = new Node;
ptr = parent->left;
} else {
parent->right = new Node;
ptr = parent->right;
}
store d in ptr node;
}
}
remove(Key k)
left = true;
parent = 0;
ptr = root;
while (ptr != 0 && ptr->key != k) {
parent = ptr;
if (ptr->key > k) {
ptr = ptr->left;
left = true;
} else {
ptr = ptr->right;
left = false;
}
}
if (ptr == 0)
throw exception of not found
else {
if (ptr->left == 0) {
if (left)
parent->left = ptr->right;
else
parent->right = ptr->right;
delete ptr;
} else if (ptr->right == 0) {
if (left)
parent->left = ptr->left;
else
parent->right = ptr->left;
delete ptr;
} else {
parent = ptr;
victim = ptr->right;
left = false;
while (victim->left != 0) {
parent = victim;
victim = victim->left;
left = true;
}
swap the data in ptr and victim;
if (left)
parent->left = victim->right;
else
parent->right = victim->right;
delete victim;
}
}