BST ——binary search tree
为什么叫二叉排序树?
因为BST的中序序列是一个有序序列,所以对于一个任意的关键字序列构造一颗二叉排序树,实质就是对其进行排序,使其变为有序序列
特点:
- 从BST的构造可以看出,任何结点都是作为叶子结点插入的
- 对于同一组关键字集合,若排列顺序不同,本节的算法生成的BST可能不同,查找效率也就因此不同
- 高度越小的BST,查找效率越高。
- 按照中序遍历可得到有序序列
typedef int keytype;
typedef struct node{
keytype key;
node *lc, *rc;
}BSTNode;
bool InsertBST(BSTNode *&bt, keytype k){//bt must be reference type or second rank pointer
if(bt == NULL){//allow insert
bt = (BSTNode *)malloc(sizeof(BSTNode));
bt->key = k;
bt->lc = bt->rc = NULL;
return true;
}
if(bt->key == k) return false;
if(k < bt->key) return InsertBST(bt->lc, k);
else return InsertBST(bt->rc, k);
}
BSTNode *CreateBST(int a[], int n){
BSTNode *bt = NULL;//
for(int i = 0; i < n; i++)
InsertBST(bt, a[i]);//apparently bt will be changed
return bt;//return the changed bt
}
void DispBST(BSTNode *bt){// output in parenthesized notation//括号表示法
if(bt != NULL){
cout << bt->key;
if(bt->lc != NULL || bt->rc != NULL){
cout << "(";
DispBST(bt->lc);
if(bt->rc != NULL) cout << ",";
DispBST(bt->rc);
cout << ")";
}
}
}
BSTNode *SearchBST(BSTNode *bt, keytype k){
if(bt == NULL || bt->key == k) return bt;
if(k < bt->key) return SearchBST(bt->lc, k);
else return SearchBST(bt->rc, k);
}
BSTNode *SearchBST_WithParentNode(BSTNode *bt, keytype k, BSTNode *f1, BSTNode *&f){
//f1: middle parameter f: return the parent node
if(bt == NULL){
f = NULL;
return NULL;
}
else if(k == bt->key){
f = f1;
return bt;
}
else if(k < bt->key) return SearchBST_WithParentNode(bt->lc, k, bt, f);
else return SearchBST_WithParentNode(bt->rc, k, bt, f);
}
int main() {
BSTNode *bt;
//int path[100];
keytype k = 6;//search term is 6
int a[] = {4,9,0,1,8,6,3,5,2,7};
int n = 10;
cout << "1. Create a binary search tree..." << endl;
bt = CreateBST(a, n);
cout << "2. Display BST: ";
DispBST(bt);
cout << endl;
BSTNode *f;
cout << "3. Search a key term... ";
//cout << SearchBST(bt, 5) -> key << endl;
cout << SearchBST_WithParentNode(bt, 6, NULL, f) -> key;//lack of robustness
return 0;
}