求二叉树的深度
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
输入
输入数据有多组,输入T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
输出
输出二叉树的深度。
示例输入
2
dbgeafc
dgebfca
lnixu
linux
示例输出
4
3
提示:这一篇和数据结构实验之求二叉树后序遍历和层次遍历差不多,一个是通过前中求树,一个是通过中后求树,一步一步的在纸上写一下就可以发现其中的奥秘;
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i,depth;
typedef char element;
typedef struct BiTnNode
{
element data;
BiTnNode *rchild,*lchild;
} BiTnNode,*BiTree;
BiTree CreateTree(int n,char a[],char b[])
{
BiTree T;
if(n==0)
return NULL;
char *p;
T=new BiTnNode;
T->data=b[n-1];///后序的第一个作为树根;
//printf("%c\n",b[n-1]);
for(p=a; *p!='\0'; p++)
if(*p==b[n-1])///在中序中寻找根的两个子树的分界线t;
break;
int t;
t=p-a;
T->lchild=CreateTree(t,a,b);///t的意义是根的左子树有多少结点,并且下一结点的是b[t-1],a的意思是从a[0]开始找b[t-1],b的意思是从b[0]开始;
T->rchild=CreateTree(n-t-1,a+t+1,p+1);///n-t-1的意思是右子树有多少结点,并且下一个结点是b[n-t-1-1],就是跳过了左子树结点和根的个数;a+t+1是指只从右子树部分查找b[n-t-1];p+1是也只从右子树部分查找;
return T;
}
int Depth(BiTree T)
{
if(T==NULL)
depth=0;
else
{
int m=Depth(T->lchild);
int n=Depth(T->rchild);
depth=1+(m>n?m:n);
}
return depth;
}
int main()
{
char a[55],b[55];
int n;
scanf("%d\n",&n);
while(n--)
{
scanf("%s%s",a,b);
int m=strlen(a);
BiTree T;
T=CreateTree(m,a,b);
int t=Depth(T);
printf("%d\n",t);
}
return 0;
}