#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
typedef struct node *link;
struct node{
int value;
link l;
link r;
int count;
};
static link head,z;
link NEW(int value,link l,link r,int count)
{
link x = new node;
x->count = count;
x->l = l;
x->r = r;
x->value = value;
return x;
}
void init()
{
head = (z=NEW(0,0,0,0));
}
int getCount()
{
return head->count;
}
int Search(link h,int key)
{
if(h==z){
cout<<"tree is null"<<endl;
exit(-1);
}
if(key < h->value){
return Search(h->l,key);
}
else if(key > h->value){
return Search(h->r,key);
}else
{
return h->value;
}
}
link Insert(link h,int key)
{
if(h==z){
return NEW(key,z,z,1);
}
if(h->value > key)
{
h->l = Insert(h->l,key);
}
else{
h->r = Insert(h->r,key);
}
h->count++;
return h;
}
int main()
{
init();
srand(time(0));
for(int i=1;i<=15;i++)
{
head = Insert(head,i);
//这个不能直接写成Insert(head,i);
}
cout<<endl;
cout<<getCount()<<endl;
for(i=0;i<15;i++)
{
cout<<Search(head,i)<<" ";
}
cout<<endl;
return 0;
}
#include <iostream>
#include<time.h>
#include<stdlib.h>
using namespace std;
typedef struct node *link;
struct node{
int value;
link l;
link r;
int count;
};
static link head,z;
link NEW(int value,link l,link r,int count)
{
link x = new node;
x->count = count;
x->l = l;
x->r = r;
x->value = value;
return x;
}
void init()
{
head = (z=NEW(0,0,0,0));
}
int getCount()
{
return head->count;
}
int Search(link h,int key)
{
if(h==z){
cout<<"tree is null"<<endl;
exit(-1);
}
if(key < h->value){
return Search(h->l,key);
}
else if(key > h->value){
return Search(h->r,key);
}else
{
return h->value;
}
}
link Insert(link h,int key)
{
if(h==z){
return NEW(key,z,z,1);
}
if(h->value > key)
{
h->l = Insert(h->l,key);
}
else{
h->r = Insert(h->r,key);
}
h->count++;
return h;
}
link Insert_v1(link &h,int key)
{
link p,x;
int y=0;
if(h==z){
return (h=NEW(key,z,z,1));
}
x=h;
p=h;
while(x!=z)
{
p=x;
x->count++;
if(key>x->value){
x=x->r;
}
else{
x=x->l;
}
}
x = NEW(key,z,z,1);
if(key > p->value){
p->r = x;
}
else{
p->l = x;
}
return h;
}
int main()
{
init();
srand(time(0));
for(int i=1;i<=15;i++)
{
head = Insert_v1(head,i);
//head = Insert(head,i);
}
cout<<getCount()<<endl;
for(i=1;i<=15;i++)
{
cout<<Search(head,i)<<" ";
}
cout<<endl;
return 0;
}