查找代码题汇总

查找代码题汇总

1.顺序表递增有序,设计算法再最少的时间内查找值为x的元素。若找到,则将其与后继元素位置交换,否则按照递增顺序插入顺序表。

void search(SqList &L, int x){
	int low=0, high=L.length-1;
	int mid, temp;//
	while(low <= high){
		mid = (low+high)/2;
		if(L.data[mid] == x){
			break;
		}else if(L.data[mid] > x){
			high = mid - 1;
		}else{
			low = mid + 1;
		}
	}
	if(L.data[mid]==x && mid!=L.length-1){
		temp = L.data[mid];
		L.data[mid] = L.data[mid+1];
		L.data[mid+1] = temp;
	}
	if(low > high){//
		for(int i=L.length-1; i>high; i--){
			L.data[i+1] = L.data[i];
		}
		L.data[high+1] = x;
		L.length++;//
	}
}

4.判断给定二叉排序树是否是二叉(搜索)排序树

//法一(不好理解,直接记住)
//pre为左子树中最大的值(也就是根节点的中序前驱)
int judgeBST(BTNode *root, int &pre){
	if(root == null){
		return 1;
	}
	int a = judgeBST(root->lchild, pre);
	if(a==0 || pre>=root->data){
		return 0;
	}
	pre = root->data;
	int b = judgeBST(root->rchild, pre);
	return b;
}
//法二(好理解)
//low是无穷小,high是无穷大
int func(BTNode *root, int low, int high){
	if(root == null){
		return 1;
	}
	if(root->data>=high || root->data<=low){
		return 0;
	}
	int a = func(root->lchild, low, root->data);
	int b = func(root->rchild, root->data, high);
	return a&&b;
}

6.求出指定结点在给定二叉排序树的层次

int level(BTNode *p, int k){
	int n = 1;
	if(p != null){
		while(p->data != k){
			if(k < p->data){
				p = p->lchild;
			}else{//
				p = p->rchild;
			}
			n++;
		}
	}
	return n;
}

7.输出二叉搜索树中所有值大于key的结点

void func(BTNode *p, int key){
	if(p != null){
		func(p->lchild, key);
		if(p->data > key){
			cout << p->data << "";
		}
		func(p->rchild, key);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

和安韩Pro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值