#include<iostream>
using namespace std;
struct Node
{
char data;
Node *lc;
Node *rc;
};
Node* create()
{
Node* p=(Node*)malloc(sizeof(Node)),*temp;
temp=p;
char ch='a';
temp->data=ch;
temp->lc=(Node*)malloc(sizeof(Node));
temp->rc=(Node*)malloc(sizeof(Node));
temp->lc->data=++ch;
temp->rc->data=++ch;
temp=p->lc;
temp->lc=(Node*)malloc(sizeof(Node));
temp->rc=(Node*)malloc(sizeof(Node));
temp->lc->data=++ch;
temp->rc->data=++ch;
temp->lc->lc=NULL;
temp->lc->rc=NULL;
temp->rc->lc=NULL;
temp->rc->rc=NULL;
temp=p->rc;
temp->lc=(Node*)malloc(sizeof(Node));
temp->rc=(Node*)malloc(sizeof(Node));
temp->lc->data=++ch;
temp->rc->data=++ch;
temp->lc->lc=NULL;
temp->lc->rc=NULL;
temp->rc->lc=NULL;
temp->rc->rc=NULL;
return p;
}
void xiangen(Node* head)//先根遍历
{
if(head!=NULL)
{
cout<<head->data<<",";
xiangen(head->lc);
xiangen(head->rc);
}
}
void zhonggen(Node* head)//中根遍历
{
if(head!=NULL)
{
zhonggen(head->lc);
cout<<head->data<<",";
zhonggen(head->rc);
}
}
void hougen(Node* head)//后根遍历
{
if(head!=NULL)
{
hougen(head->lc);
hougen(head->rc);
cout<<head->data<<",";
}
}
Node* find(Node* head,char x)
{
if(head!=NULL)
{
if(head->data==x)
return head;
Node *temp=find(head->lc,x);
if(temp!=NULL)
return temp;
else
return find(head->rc,x);
}
return NULL;
}
int height(Node* head)
{
int lc,rc;
if(head==NULL) return 0;
else
{
lc=height(head->lc);
rc=height(head->rc);
return (lc>rc)?(lc+1):(rc+1);
}
}
int main()
{
Node* p=create();
Node* t;
cout<<"先根遍历:"<<endl;
xiangen(p);cout<<endl;
cout<<"中根遍历:"<<endl;
zhonggen(p);cout<<endl;
cout<<"后根遍历:"<<endl;
hougen(p);cout<<endl;
t=find(p,'g');
cout<<"查找到的数据:"<<t->data<<endl;
cout<<"树高:"<<height(p)<<endl;
return 0;
}