#include<stdlib.h>
#include<string.h>
typedef char elemtype;
typedef struct node{
elemtype data;
node *firstchild,*nextsibling;
} *root,*tree;
int inittree(tree &T)
{
T=(node*)malloc(sizeof(node));
if(!T) return 0;
T->data='q';
T->firstchild=T->nextsibling=NULL;
return 1;
}
void preorder(tree t,void visit(elemtype))
{
if(t)
{
visit (t->data);
preorder(t->firstchild,visit);
preorder(t->nextsibling,visit);
}
}
void preorderlists(tree t,void visit(elemtype))
{
tree p;
if(!t) return;
visit (t->data);
p=t->firstchild;
if(p)
cout<<"(";
while(p)
{
preorderlists(p,visit);
if(p)
cout<<',';
else
cout<<")";
}
}
int createnode(tree &T,elemtype s)
{
T=(node*)malloc(sizeof(node));
if(!T) return 0;
T->firstchild=T->nextsibling=NULL;
T->data=s;
return 1;
}
void creattree(tree &t,char s[],int &i,int len)
{
tree p;
i++;
if(i<len)
{
if(s[i]=='#') {t=NULL;return;}
createnode(t,s[i]);
if(i+1<len&&s[i+1]=='(')
{
i++;
creattree(t->firstchild,s,i,len);
}
p=t->firstchild;
while(i+1<len&&s[i+1]==',')
{
i++;
creattree(p->nextsibling,s,i,len);
p=p->nextsibling;
}
i++;
}
}
void createtree(tree &t,char s[])
{
int i=-1;
int len=strlen(s)-1;
creattree(t,s,i,len);
}
----------------解决方案--------------------------------------------------------
这是主程序
#include<iostream.h>
#include"04072209tree.h"
void main()
{
void visit(char s);
int getdegree(tree t);
tree t;
char s[]="a(b(e,f),c(g),d)";
createtree(t,s);
//preorder(t,visit);
// cout<<endl;
//cout<<getdegree(t);
}
int getdegree(tree t)
{
int d=0,m=0;
tree p;
if(!t) return 0;
else
{
p=t->firstchild;
for(;p;p=p->nextsibling)
m++;
for(p=t->firstchild;p;p=p->nextsibling)
{
d=getdegree(p);
if(d>m) m=d;
}
return d;
}
}
void visit(char s)
{
cout<<s;
}
----------------解决方案--------------------------------------------------------