2.4 - Binary Search Tree
二元搜尋樹介紹及相關演算法
1. 定義
是一個binary tree,可以為空
left-children < root
right-children > root
left-children和right-children都是binary search tree
10
/ \
5 12
/ \ \
3 8 15
/
14
2. 相關演算法
2.1 在二元搜尋樹中尋找x
若b是空樹,搜尋失敗。
若x等於b的根節點的資料域之值,尋找成功。
若x小於b的根節點的資料域之值,搜尋左子樹。
若x大於b的根節點的資料域之值,尋找右子樹。
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;
}
時間複雜度分析:
worst case: O(n) in skewed binary tree
best case: O(logn) in complete/full binary tree
2.2 在二元搜尋樹中刪除節點x
在BST中尋找x的位置
如果x是leaf,直接刪除
如果x是degree為1的節點
刪除x
將x的父點指向x的pointer指向x的子點
如果x是degree為2的節點
找到x的左子樹中的最大值/右子樹中的最小值y
y回到step2/step3
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;
}
}
}
2.3 在二元搜尋樹中加入節點x
若是空樹,則將x作為root插入
若x小於根節點,則把x插入到左子樹中
若x大於根節點,則把x插入到右子樹中(新插入節點總是在leaf)
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);
}
}
}
Last updated