求二叉树的深度
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
输入
输入数据有多组,输入T组数据。每组数据包括两个长度小于<font face="\"Times" new="" roman,="" serif\"="" style="padding: 0px; margin: 0px;">50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
输出
输出二叉树的深度。
示例输入
2 dbgeafc dgebfca lnixu linux
示例输出
4 3
此题目和二叉树后序遍历与层次遍历思路差不多,详见本人同类文章,http://blog.csdn.net/qq_35354855/article/details/52191459
此处不再多说。
下面上代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
char data;
struct node *lchild,*rchild;
}node,*nodeptr;
int depth(struct node *T)
{
int de,del,der;
if(!T)de=0;
else
{
del=depth(T->lchild);
der=depth(T->rchild);
de=1+(del>der?del:der);
}
return de;
}
struct node *Creat(char *hou,char *zhong,int n)
{
struct node *T;
int k;
char *p;
if(n<=0)return NULL;
T=(struct node *)malloc(sizeof(struct node));
T->data=*hou;
for(p=zhong;p;p++)
{
if(*p==*(hou))
break;
}
k=p-zhong;
T->lchild=Creat(hou-n+k,zhong,k);
T->rchild=Creat(hou-1,p+1,n-k-1);
return T;
}
int main()
{
int t,i;
struct node *T;
scanf("%d",&t);
char zhong[55],hou[55];
while(t--)
{
scanf("%s",zhong);
scanf("%s",hou);
i=strlen(zhong);
T=Creat(&hou[i-1],zhong,i);
printf("%d\n",depth(T));
}
return 0;
}
在代码第61行,如果改成T=Creat(hou,zhong,i);
则Creat()就可以变成:
struct node *Creat(char *hou,char *zhong,int n)
{
struct node *ptr;
char *r;
int k;
if(n<=0)return 0;
ptr=(struct node *)malloc(sizeof(struct node));
ptr->data=*(hou+n-1);
for(r=zhong;r<zhong+n;r++)
{
if(*r==*(hou+n-1))break;
}
k=r-zhong;
ptr->lchild=Creat(hou,zhong,k);
ptr->rchild=Creat(hou+k,r+1,n-k-1);
return ptr;
}
这样编译过后也是正确的答案