A(B(D(,G)),C(E,F))
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cstdlib>
using namespace std;
const int MaxSize=100;
typedef struct Node{
int data;
struct Node *l;
struct Node *r;
}BTNode;
void CreateBTree(BTNode * &b,char str[]){
BTNode* St[MaxSize],*p;
int top=-1,k,j=0;
char ch;
b=NULL;
ch=str[j];
while(ch!='\0'){
switch(ch){
case '(':top++;St[top]=p;k=1;break;
case ')':top--;break;
case ',':k=2;break;
default:p=(BTNode *)malloc(sizeof(BTNode));
p->data=ch;
p->l=p->r=NULL;
if(b==NULL)
b=p;
else{
switch(k){
case 1:St[top]->l=p;break;
case 2:St[top]->r=p;break;
}
}
}
j++;
ch=str[j];
}
}
void InOrder(BTNode *b){
if(b!=NULL){
printf("%c",b->data);//先序
InOrder(b->l);
//printf("%c",b->data);//中序
InOrder(b->r);
//printf("%c",b->data);//后序
}
}
int BTHeight(BTNode *b){
int l,r;
if(b==NULL) return 0;
else{
l=BTHeight(b->l);
r=BTHeight(b->r);
return (l>r)?(l+1):(r+1);
}
}
BTNode *FindNode(BTNode *b,char x){
BTNode *p;
if(b==NULL)
return NULL;
else if(b->data==x)
return b;
else{
b=FindNode(b->l,x);
if(p!=NULL)
return p;
else
return FindNode(b->r,x);
}
}
void DestroyBTree(BTNode *&b){
if(b!=NULL){
DestroyBTree(b->l);
DestroyBTree(b->r);
free(b);
}
}
int main(){
char str[100];
cin>>str;
BTNode *t;
CreateBTree(t,str);
cout<<"该树的高度为"<<BTHeight(t)<<endl;
cout<<"前序遍历该树:";
InOrder(t);
cout<<endl;
cout<<"输入要查询的值";
char x;
getchar();
scanf("%c",&x);
BTNode *p=FindNode(t,x);
DestroyBTree(t);
return 0;
}