#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