二分查找与二叉搜索树的查找插入与删除(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;
}