10
/ \
5 12
/ \ \
3 8 15
/
14
bool SearchBST(bt_tree *bst, int x){
if (bst != NULL){
if (x > bst->Data) SearchBST(bt->rchild, x);
if (x < bst->Data) SearchBST(bt->lchild, x);
if (x == bst->Data) return True;
}
return False;
}
void DeleteBST(bt_tree *bst, int x){
if (bst != NULL){
if (x > bst->Data) SearchBST(bt->rchild, x);
if (x < bst->Data) SearchBST(bt->lchild, x);
if (x == bst->Data) return Delete(bst);
}
}
void Delete(bt_tree *bst){
bt_tree *temp;
if (bst->lchild == NULL && bst->child == NULL){
bst = NULL;
}
else if (bst->lchild != NULL && bst->rchild == NULL){
temp = bst->lchild;
bst->Data = temp->Data;
bst->lchild = temp->lchild;
bst->rchild = temp->rchild;
temp = NULL;
}
else if (bst->lchild == NULL && bst->rchild != NULL){
temp = bst->rchild;
bst->Data = temp->Data; //將子節點的值取代x
bst->lchild = temp->lchild;
bst->rchild = temp->rchild;
temp = NULL;
}
else{ //以左子樹的最大值取代x
bt_tree *parent = bst;
temp = bst->lchild;
while(temp->rchild != NULL){
parent = temp;
temp = temp->rchild; //左子樹的最大值
}
bt->Data = temp->Data;
if (bst != parent){
parent->rchild = temp->lchild;
}
else{ //左子樹是skewed binary tree
parent->lchild = temp->lchild;
}
}
}
void insertBST(bt_tree *bst, int x){
if (bst == NULL){
bst->Data = x;
}
else{
if (x > bst->Data){
insertBST(bst->rchild, x);
}
else{
insertBST(bst->lchild, x);
}
}
}