Vous êtes sur la page 1sur 6

Binary Search Tree (BST)

A Binary Tree with specific properties, i.e., for each


node X in the tree:
1. The values of all nodes in the left subtree must be
smaller than the value of X
2. The values of all nodes in the right subtree must
be larger than the one of X
6 6

2 8 2 8

1 4 1 4

3 3 7

Benefit
™ Searching a certain node in the tree will be very
efficient and fast

Operations in BST
™ Insert operation
™ Delete operation
™ Other support operation:

Digitally signed by Nur Hadisukmana

Nur Hadisukmana DN: CN = Nur Hadisukmana, C = ID, O = President University, OU = IT Program


Reason: I am the author of this document
Date: 2008.07.16 08:36:10 +07'00'
BST Data Structure
struct SNode{
int data; SNode * Root;
SNode *left,*right;
};

Algorithm

SNode* Insert(int dat,SNode* T)


{
SNode* temp;

if(!T){
temp = new SNode;
temp->data = dat;
temp->left = 0;
temp->right = 0;
return temp;
}else{
if(dat < T->data)
T->left = Insert(dat,T->left);
else if(dat > T->data)
T->right = Insert(dat,T->right);
return T;
}
}
SNode* Delete(int dat,SNode* n)
{
SNode* cur;

if(n){
if(dat < n->data)
n->left = Delete(dat,n->left);
else if(dat > n->data)
n->right = Delete(dat,n->right);
else{
if(n->left AND n->right)
FindMin(n);
Else if(n->left){
cur = n;
n = n->left;
delete cur;
}else
cur = n;
n = n->right;
delete cur;
}
}
return n;
}else
return 0;
}
void Insert(int dat, SNode* r)
{ if(left)
SNode* prev = 0; prev->left = temp;
SNode* cur = r; else
SNode* temp; prev->right = temp;
bool left; }
}
while(cur){ }
prev = cur;
if(dat < cur->left){
left = TRUE;
cur = cur->left;
}else if(dat > cur->right){
left = FALSE;
cur = cur->right;
}else
exit while;
}
if(!cur){
temp = new SNode;
temp->data = dat;
temp->left = 0;
temp->right = 0;
if(!prev)
cur = temp;
else{
void Delete(int dat, SNode*r)
{ prev->right = temp;
SNode *prev = 0; delete cur
SNode *cur = r; }
SNode *temp = 0; bool left; }
}
while(cur AND
dat != cur->data){
prev = cur;
if(dat < cur->left){
left = TRUE;
cur = cur->left;
}else if(dat > cur->right){
left = FALSE;
cur = cur->right;
}
}
if(cur){
if(cur->left AND
cur->right)
FindMin(cur);
else{
if(cur->left)
temp = cur->left;
else
temp = cur->right;
if(left)
prev->left = temp;
else
void FindMin(SNode* n)
{
SNode* prev = n;
SNode* cur = n->right;

while(cur->left){
prev = cur;
cur = cur->left;
}
if(prev == n)
prev->right = cur->right;
else
prev->left = cur->right;
n->data = cur->data;
delete cur;
}

void FindMax(SNode* n)
{

Vous aimerez peut-être aussi