二分查找与二叉搜索树的查找插入与删除(c)

二分查找与二叉搜索树的查找插入与删除(c)

1,静态查找表二分查找c语言实现,(已排好序)

int Search_bin(int *a, int x) {//传入需要查找的数组,查找并返回索引
	int low = 0;
	int size = 0;
	for (int i = 0; i < 11; i++) {
		size++;
	}
	int high = size;    //获得数组长度
	while (low <= high) {
		int mid = (low + high) / 2;
		if (a[mid] < x) low = mid + 1;
		else if(a[mid]>x) high = mid - 1;
		else return mid;
	}
	return -1;    //没找到则返回-1
}

动态查找(对象集合存在插入删除操作)
1.二叉搜索树,
性质:若存在左子树则左子树所有节点小于根节点,若存在右子树,则右子树的所有节点值都大于根节点值,且其左右子树也都为二叉排序树
其结构与二叉树相同
基本算法:
1.查找

//在二叉树内递归查找x
tree find(tree t, int x) {
	if (t->data > x)
	{
		find(t->lchild, x);
	}
	else if(t->data<x) find(t->rchild, x);
	else return t;
}
//非递归查找
tree find2(tree t, int x) {
	while (t) {
		if (t->data > x)
		{
			t=t->lchild;
		}
		else if (t->data < x) t=t->rchild;
		else return t;
	}
}
//查找线索二叉树最大值,最小值同理
int maxtree(tree t) {
	if (!t) return -1;//树为空
	else {
		while (t->rchild) t = t->rchild;
	}
	return t->data;
}

//在线索二叉树里插入以及删除值,这里要特别注意函数调用时返回值的使用,不能只靠结构指针来改变实参,当传入的实参为空指针时,并没有内存空间,对形参的操作并不能影响实参
在线索二叉树中递归找到合适的位置,再新建节点插入值,显然按照定义来说插入的值再叶子节点处

//在线索二叉树里插入值
tree insert(tree t,int x) {  //注意在函数调用时使用返回值
	if (!t) {
		t = (tree)malloc(sizeof(struct bintree));
		t->data = x;
		t->lchild = t->rchild = NULL;
	}
	else
	{
		if (t->data > x) t->lchild=insert(t->lchild,x);
		else if (t->data < x) t->rchild=insert(t->rchild,x);
	}
	return t;
}

在线索二叉树内删除值

tree deletetree(tree t, int x) {
	if (t==NULL) {
		printf("值不存在");
	}//值不存在
	else if (x > t->data) {	//查找到要删除的元素位置
		t->rchild = deletetree(t->rchild,x);
	}
	else if (x < t->data) {
		t->lchild = deletetree(t->lchild,x);
	}
	else {
		if(t->lchild&&t->rchild) {  //左右子树都不空,找左子树的最大值或右子树的最小值
			int z = maxtree(t->lchild);//查找最大值
			t->data = z;
			t->lchild = deletetree(t->lchild, z);
		}
		else {
			if (!t->lchild) {//左子树为空时,包含左右子树都为空时的情况
				t = t->rchild;
			}
			else if( !t->rchild) {//右子树为空时
				t = t->lchild;
			}
		}
	}
	return t;
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值