王道OnlineJudge 课时15作业

#include <stdio.h>
#include <stdlib.h>
typedef int KeyType;
typedef struct BSTNode{
	KeyType key;
	struct BSTNode *lchild, *rchild;
}BSTNode, *BiTree;
int BST_Insert(BiTree &T,KeyType k)
{
	BiTree TreeNew=(BiTree)calloc(1,sizeof(BSTNode));//新结点申请空间
	TreeNew->key=k;//把值放入
	if(NULL==T){
		T=TreeNew;
		return 1;//代表插入成功
	}
	BiTree p=T,parent;//p用来查找树
	while(p){
		parent=p;//parent用来存p的父亲
		if(k>p->key){
			p=p->rchild;
		}else if(k<p->key){
			p=p->lchild;
		}else{
			return -1;//相等元素不可放入查找树,考研不会考相等元素放入问题
		}
	}
	//接下来要判断放到父亲的左边还是右边
	if(k>parent->key){
		parent->rchild=TreeNew;
	}else{
		parent->lchild=TreeNew;
	}
	return 1;
}
void Creat_BST(BiTree &T,KeyType str[],int n)
{
	for(int i=0;i<n;i++){
		BST_Insert(T,str[i]);//把某一个结点放入二叉查找树
	}
}
void InOrder(BiTree T,int str[])	//中序遍历
{
	static int i = 0;//静态局部变量,只会被初始化一次
	if(T!=NULL){
		InOrder(T->lchild,str);
		printf("%3d",T->key);
		str[i++]=T->key;
		InOrder(T->rchild,str);
	}
}
int BinarySearch(int str[],int len,int key)//折半查找
{
	int low = 0;
	int high = len-1;
	int mid;
	while(low<=high){
		mid = (low+high)/2;
		if(str[mid]==key)
			return mid;//等于找到了
		else if(str[mid]>key)
			high = mid - 1;
		else
			low = mid +1;
	}
	return -1;
}

int main()
{
	BiTree T = NULL;//树根
	BiTree parent;//存储父亲结点的值
	BiTree search;
	KeyType str[10];
	for(int i=0;i<10;i++){
		scanf("%d",&str[i]);
	}
	Creat_BST(T,str,10);
	InOrder(T,str);	//中序遍历把有序的结果存入str数组中
	printf("\n");
	int pos=BinarySearch(str,10,21);
	printf("%d",pos);
	return 0;
}
87  7 60 80 59 34 86 99 21  3
  3  7 21 34 59 60 80 86 87 99
2

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值