二叉搜索树的基本操作

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; 
}

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值