2--搜索树

搜索树

struct tnode{
	element data;
	struct tnode *left;
	struct tnode *right;
}; 

typedef struct tnode *bintree;
typedef struct tnode *position;

bintree bst;

//递归 
position find(element x,bintree bst){
	if(!bst){
		return NULL;
	}
	if(x<bst->data){
		return find(x,bst->left);
	}else if(x>bst->data){
		return find(x,bst->right);
	}else{
		return bst;
	}
}

//迭代 
position find(element x,bintree bst){
	while(bst){
		if(x>bst->data){
			bst=bst->right;
		}else if(x<bst->data){
			bst=bst->left;
		}else{
			break;
		}
	}
	return bst;
}

//迭代 
position findmax(bintree bst){
	if(bst){
		while(bst->right){
			bst=bst->right; 
		}
	}
	return bst;
}
//递归
position findmin(bintree bst){
	if(!bst) return bst;
	else if(!bst->left) return bst;
	else return find(bst->left);
} 

//插入
bintree insert(element x,bintree bst){
	if(!bst){
		bst=malloc(sizeof(struct tnode));
		bst->data=x;
		bst->left=bst->right=NULL;
	}
	while(bst){
		if(x>bst->data){
			bst->right=insert(x,bst->right);
		}else if(x<bst->data){
			bst->left=insert(x,bst->left); 
		}else
	}
	return bst;
} 
//删除
bintree deleteq(bintree bst,element x){
	position temp;
	if(!bst){
		printf("not find");
	}else{
		if(x>bst->data){
			bst->right=deleteq(bst->right,x);
		}else if(x<bst->data){
			bst->left=deleteq(bst->left,x);
		}else{
			if(bst->left&&bst->right){
				temp=findmax(x,bst->left);
				bst->data=temp->data;
				bst->left=deleteq(bst->left,temp->data);	
			}else{
				temp=bst;
				if(!bst->left){
					 bst=bst->right;
				}else{
					bst=bst->left;
				}
				free(temp);
		}
	}
	return bst;
} 

bintree deleteq(element x,bintree bst){
	position=temp;
	if(!bst){
		printf("not find");
	}
	else{
		if(x>bst->data){
			bst->right=deleteq(x,bst->right);
		}else if(x<bst->data){
			bst->left=deleteq(x,bst->left);
		}else{
			if(bst->left&&bst->right){
				temp=findmin(bst->right);
				bst->data=temp->data;
				bst->right=deleteq(x,bst->data);
			}else{
				temp=bst;
				if(!bst->left){
					bst=bst->right;
				}else{
					bst=bst->left;
				}
				free(temp);
			}
		}
	}
	return bst;

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值