void CreatBTNode(BTNode *&b,char *str)
{
BTNode *st[MaxSize],*p=NULL;
int top=-1,k;
char ch;
b=NULL;
ch=*str;
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->lchild=p->rchild=NULL;
if(b==NULL)
b=p;
else
{
switch(k)
{
case 1:st[top]->lchild=p;break;
case 2:st[top]->rchild=p;break;
}
}
}
str++;
ch=*str;
}
}
int Level(BTNode * b,char X,int h)
{
int l;
if(b==NULL)
return 0;
else if(b->data==X)
return h;
else
{
//cout<<b->data;
l=Level(b->lchild,X,h+1);
if(l!=0)
{
cout<<b->data;//(1)
return l;
}
else
{
cout<<b->data;//(2)
return Level(b->rchild,X,h+1);
}
}
}
void main()
{
BTNode *b;
CreatBTNode(b,"A(B(D(I),E(G,H)),C(,F))");
int h=1;
char x;
cout<<"node is ";
cin>>x;
h=Level(b,x,h);
if(h==0)
cout<<x<<" is not found"<<endl;
else
cout<<x<<" is in the "<<h<<" level"<<endl;
}
x=I时,有且只有(1)处的输出为DBA
x=H,(1)输出为A;(2)输出为IDBGE,按序输出地顺序为IDBGEA
通过好好体会其执行顺序,对递归的运算会渐渐明晰