求二叉樹的深度
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
#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);
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;
}
這樣編譯過後也是正確的答案