第1个回答 推荐于2017-09-24
typedef struct node
{
char data;
struct node *lchild,*rchild;
}bitree;
bitree *root=NULL;
//创建树
bitree *CreateTree(char *sInPut)
{
bitree *root,*s;
bitree *Q[128];
int front,rear;
root=NULL;
front=1;
rear=0;
char temp[128],*p;
memset(temp,0,128);
strcpy(temp,sInPut);
p=temp;
while(strlen(p)>0)
{
s=NULL;
if(*p!='@')
{
s=(bitree*)malloc(sizeof(bitree));
s->data=*p;
s->lchild=NULL;
s->rchild=NULL;
}
rear++;
Q[rear]=s;
if(rear==1)
{
root=s;
}
else
{
if(s && Q[front])
{
if(rear%2==0)
Q[front]->lchild=s;
else
Q[front]->rchild=s;
}
if(rear%2==1) front++;
}
p+=2;
}
return root;
}
//释放树
void freetree(bitree *root)
{
if(root!=NULL)
{
freetree(root->lchild);
freetree(root->rchild);
free(root);
}
}
//前序遍历
void preorder(bitree *root)
{
if(root!=NULL)
{
printf("%c\t",root->data);
preorder(root->lchild,sOutPut);
preorder(root->rchild,sOutPut);
}
}
//中序遍历
void inorder(bitree *root)
{
if(root!=NULL)
{
inorder(root->lchild,sOutPut);
printf("%c\t",root->data);
inorder(root->rchild,sOutPut);
}
}
//后序遍历
void postorder(bitree *root)
{
if(root!=NULL)
{
postorder(root->lchild,sOutPut);
postorder(root->rchild,sOutPut);
printf("%c\t",root->data);
}
}
//层次遍历
void PrintTree(bitree *root)
{
CString sOutPut;
char temp[128];
bitree *Q[128],*s;
int front,rear;
front=0;
rear=0;
sOutPut.Empty();
Q[rear++]=root;
while(rear>front)
{
printf("%c\t",Q[front]->data);
sOutPut=temp;
s=Q[front++];
if(s->lchild!=NULL)
Q[rear++]=s->lchild;
if(s->rchild!=NULL)
Q[rear++]=s->rchild;
}
}
//树叶子数
void countleaf(bitree *root,int &count)
{ if(root!=NULL)
{ if((root->lchild==NULL)&&(root->rchild==NULL))
{ count++;
return;
}
countleaf(root->lchild,count);
countleaf(root->rchild,count);
}
}
//树深度
void treedepth(bitree *root,int l,int &h)
{ if(root!=NULL)
{ l=l+1;
if(l>h) h=l;
treedepth(root->lchild,l,h);
treedepth(root->rchild,l,h);
}
}本回答被提问者采纳