/**任何一个结点的值域都比它的右子树小,比它的左子树大,我们叫它二叉搜索树**/
//二叉搜索数用链式存储表示
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef int Ele;
typedef struct Node{
Ele e;
struct Node *left;
struct Node *right;
}*Tree,*TNode;
//
Tree insert(Tree t,Ele e){
if(t==NULL){
t=(TNode)malloc(sizeof(struct Node));
t->e=e;
t->left=NULL;
t->right=NULL;
}else if(t->e>e)
t->left=insert(t->left,e);
else if(t->e<e)
t->right=insert(t->right,e);
//printf("%d\n",t->e);
return t;
}
void print(Tree t,int *n){//n为计算结点数
if(t){
printf("%d ",t->e );(*n)++;
print(t->left,n);
print(t->right,n);
}
}
int main(int argc, char const *argv[])
{
srand((unsigned) time(NULL)); //用时间做种,每次产生随机数不一样
/* code */
Tree t=NULL;
int number=0;
for(int i=0;i<300;i++){
number = rand() % 101; //产生0-100的随机数
t=insert(t,number);
}
int n=0;
print(t,&n);
printf("\n%d\n",n);
return 0;
}
//二叉搜索数用顺序存储表示
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef int Ele;
#define MAXSIZE 100
#define null -1
typedef struct{
Ele data[MAXSIZE+1];
int n;
}Tree;
Tree createtree(){
Tree h;
h.n=0;
for(int i=0;i<=MAXSIZE;i++)
h.data[i]=null;
return h;
}
void insert(Tree *tree,Ele e){
int i=1;
for(;i<=MAXSIZE&&tree->data[i]!=-1&&e!=tree->data[i];){
if(e<tree->data[i]){
i=2*i;//转到左孩子
}else if(e>tree->data[i]){
i=2*i+1;//转到y右孩子
}
if(i<=MAXSIZE&&tree->data[i]==-1)
tree->data[i]=e,tree->n++;
}
int findmin(const Tree *tree){
int i=1;
while(tree->data[2*i]!=null){
i=2*i;
}
return i;
}
void print(const Tree *t,int i){//中序遍历的结果从小到大排列
if(i<=MAXSIZE&&t->data[i]!=null)
{
print(t,2*i);
printf("%d ", t->data[i]);
print(t,2*i+1);
}
}
int main(){
srand(time(NULL));
Tree t=createtree();
for(int i=0;i<20000;i++){
insert(&t,rand()%201);
}
print(&t,1);
}
下一篇将讨论二叉搜索树的查找和删除