码迷,mamicode.com
首页 > 编程语言 > 详细

查找 - 二叉排序树查找及相关操作

时间:2016-04-23 21:31:59      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:

#include<cstdio>
#include<cstdlib>
#include<cstring>

typedef struct BiTNode{
	int data;
	struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;

//查找 
int SearchBST(BiTree T,int key,BiTree f,BiTree *p){
	if(!T){
		*p = f;
		return 0;
	}else if(key == T->data){
		*p = T;
		return 1;
	}else if(key < T->data) return SearchBST(T->lchild,key,T,p);
	else return SearchBST(T->rchild,key,T,p);
}

//插入
int InsertBST(BiTree *T,int key){
	BiTree p,s;		 
	if(!SearchBST(*T,key,NULL,&p)){ //查找不成功 
		s = (BiTree)malloc(sizeof(BiTNode));
		s->data = key;
		s->lchild = s->rchild = NULL;
		if(!p){		//根结点为空,(树不存在) 
			*T = s;	//s为根结点 
		}else if(key < p->data){
			p->lchild = s;
		} else{
			p->rchild = s;
		}
		return 1;
	}else{
		return 0;
	}
} 

//删除
int Delete(BiTree *p){
	BiTree q,s;
	if((*p)->rchild == NULL){
		q = *p;*p = (*p)->lchild;free(q);
	}else if((*p)->lchild == NULL){
		q = *p;*p = (*p)->rchild;free(q);
	}else{
		q = *p;s = (*p)->lchild;
		while(s->rchild) { //找到左子树最最右面的结点,也就是小于且最接近该结点的结点(中序前驱结点) 
			q = s; s = s->rchild;	//q 为前驱结点的父结点 
		}
		(*p)->data = s->data;
		
		//将 s 为根结点的树上接 就可以了 
		if(q != *p){
			q->rchild = s->lchild;	
		} else{
			q->lchild = s->lchild;
		}
		free(s);
	}
	return 1;
}
int DeleteBST(BiTree *T,int key){
	if(!*T) return 0;
	else{
		if((*T)->data == key){
			return Delete(T);
		}else if(key <(*T)->data){
			return DeleteBST(&(*T)->lchild,key);
		}else{
			return DeleteBST(&(*T)->rchild,key);
		}
	}
} 
int main(){
	int i;
	int key;
	int switch1;
	int a[10] = {62,88,58,47,35,73,51,99,37,93};
	BiTree T = NULL;
	
	for(i=0;i<10;i++) InsertBST(&T,a[i]); 
	while(true){
		printf("输入1:查找,输入2:删除\n"); 
		scanf("%d",&switch1);
		if(switch1 == 1){
			BiTree p = NULL; 
			scanf("%d",&key);
			if(SearchBST(T,key,NULL,&p)){
				printf("%d 查找成功!\n",p->data);
			}else{
				printf("查找失败!\n");
			}
		}else if(switch1 == 2){
			scanf("%d",&key);
			if(DeleteBST(&T,key)){
				printf("删除成功!\n");
			}else{
				printf("不存在此结点!\n");
			}
		}else{
			printf("重新输入!\n");
			continue;
		} 
		
	}
	return 0;
} 

  

查找 - 二叉排序树查找及相关操作

标签:

原文地址:http://www.cnblogs.com/zhuozhuo/p/5425489.html

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