码迷,mamicode.com
首页 > 其他好文 > 详细

二叉搜索树的随机化插入和伸展插入操作(平摊法)

时间:2015-08-20 13:07:34      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:二叉查找树排序   二叉搜索树随机化插入   二叉搜索树伸展化插入   bst随机化插入   bst伸展化插入   

源代码如下:

#include <stdlib.h>
#include <stdio.h>
//#define Key int
#define hl h->l
#define hr h->r
#define hlr h->l->r
#define hll h->l->l
#define hrr h->r->r
#define hrl h->r->l
typedef int Key;
struct Item{
	Key key;
	char c;
};
typedef struct STnode* link;
struct STnode{
	Item item ; link l,r; int N;
};

static link head , z ;
static struct Item NULLitem ;

Key key(Item item){
	return item.key;
}
//创建一个节点 
link NEW(Item item, link l,link r, int N){
	link x = (link)malloc(sizeof *x);
	x->item = item;x->l = l;x->r = r;x->N = N;
	if(head==z)head=x; //这句话不能少!!! 
	return x;
}
//初始化 
void STinit(){
	head = ( z = NEW(NULLitem,0,0,0));
}

//右旋转 顺时针旋转 
link rotR(link h){
	link x = h->l; h->l = x->r; x->r=h;
} 
//左旋转 逆时针旋转 
link rotL(link h){
	link x = h->r; h->r = x->l; x->l=h;
}

//根插入程序 
link insertT(link h, Item item){
//	Key v = key(item), t = key(h->item);
	char v = item.c, t = h->item.c;
	if(h==z)return NEW(item,z,z,1);
	if(v<t) {h->l = insertT(h->l,item); h = rotR(h); }
	else {h->r = insertT(h->r,item); h = rotL(h);}
	(h->N)++;return h;
}

//随机化插入程序 
link insertR(link h, Item item){
//	Key v = key(item), t = key(h->item);
	char v = item.c, t = h->item.c;
	if(h==z)return NEW(item,z,z,1);
	if(rand() < RAND_MAX / (h->N+1))
		return  insertR(h,item);  //使得新节点出现在树根的概率是1/(N+1) 
	if(v<t) {h->l = insertR(h->l,item); h = rotR(h); }
	else {h->r = insertR(h->r,item); h = rotL(h);}
	(h->N)++;return h;
}

//伸展插入
link splay(link h, Item item) {
	char v = item.c, t = h->item.c;
	if(h==z)return NEW(item,z,z,1);
	if(v<t){
		if(hl==z)return NEW(item,z,h,h->N+1);
		if(v<hl->item.c){
			hll=splay(hll,item); h = rotR(h);
		}else{
			hlr = splay(hlr,item); hl = rotL(hl);
		}
		return rotR(h);
	}
	else {
		if(hr==z)return NEW(item,h,z,h->N+1);
		if(v>hr->item.c){
			hrr=splay(hrr,item); h = rotL(h);
		}else{
			hrl = splay(hrl,item); hr = rotR(hr);
		}
		return rotL(h);
	}
}



//BST插入主程序 
void STinsert(Item item){  //新插入的节点都会当作根节点 
	head =  splay(head,item);
}

void sortR(link h){
	if(h==z)return;
	printf("%c ",h->item.c);	
	sortR(h->l);
	sortR(h->r);
}
//二叉搜索树排序 
void STsort(link h){
	sortR(h);
}

void test(){
	struct Item item1 = {322,'a'};
	struct Item item2 = {23,'s'};
	struct Item item3 = {2,'e'};
	struct Item item4 = {332,'r'};
	struct Item item5 = {332,'c'};
	struct Item item6 = {332,'h'};
	struct Item item7 = {112,'i'};
	STinit();
	STinsert(item1);STinsert(item2);
	STinsert(item3);STinsert(item4);
	STinsert(item5);STinsert(item6);
	STinsert(item7);
	STsort(head);
}


main(){
	test();
} 


版权声明:本文为博主原创文章,未经博主允许不得转载。

二叉搜索树的随机化插入和伸展插入操作(平摊法)

标签:二叉查找树排序   二叉搜索树随机化插入   二叉搜索树伸展化插入   bst随机化插入   bst伸展化插入   

原文地址:http://blog.csdn.net/wen942467928/article/details/47805611

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!