查找代码题汇总
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);
}
}