#include <iostream>
using namespace std;
struct Node
{
struct Node *leftchild;
struct Node *rightchild;
int data;
};
struct Node *root = NULL;
void create_search_tree(int element)
{
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = element;
temp->leftchild = temp->rightchild = NULL;
if(root==NULL)
{
root = temp;
return;
}
struct Node *pre , *current = root;
while(current!=NULL)
{
pre = current;
if(element>current->data)
{
current = current->rightchild;
}
else
{
current = current->leftchild;
}
}
if(element>pre->data)
{
pre->rightchild = temp;
}
else
{
pre->rightchild = temp;
}
}
//定义一个简单的数组栈
static struct Node* arr[200];
int top = -1;
void push(struct Node *element)
{
if(top+1==200)
{
return;
}
top++;
arr[top] = element;
}
void pop(struct Node **element)
{
if(top==-1)
{
return;
}
*element = arr[top];
top--;
}
bool is_empty()
{
return top ==-1;
}
//中根遍历一棵树,当中根遍历一棵二叉搜树时,会得到一个有序序列.
void midorder(struct Node *root)
{
struct Node *p = root;
while(!is_empty()||p!=NULL)
{
if(p!=NULL)
{
push(p);
p = p->leftchild;
}
else
{
pop(&p);
cout<<p->data<<" ";
p = p->rightchild;
}
}
}
int main()
{
int arr[16] = {12,2,1,45,23,18,67,89,9,43,65,78,67,13,24,52};
for(int i=0; i<16; i++)
{
create_search_tree(i);
}
midorder(root);
cout<<endl;
return 0;
}
void preorder(struct Node *root)
{ //先根遍历 struct Node *p = root;
while(p!=NULL || !is_empty())
//只要这两者有一个条件还不萍踪就执行.
{ if(p==NULL) { pop(&p); }
cout<data<<" "; if(p->rightchild!=NULL)
{ push(p->rightchild); }
p = p->leftchild; } }