数据结构实验之二叉树八:(中序后序)求二叉树的深度
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知一颗二叉树的中序遍历序列和后序遍历序列,求二叉树的深度。
Input
输入数据有多组,输入T,代表有T组数据。每组数据包括两个长度小于50的字符串,第一个字符串表示二叉树的中序遍历,第二个表示二叉树的后序遍历。
Output
输出二叉树的深度。
Sample Input
2
dbgeafc
dgebfca
lnixu
linux
Sample Output
4
3
Hint
Source
重点:中序后序建立二叉树
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char a[51],b[51];
int n;
struct node
{
char data;
struct node *lc;
struct node *rc;
};
struct node *creat(char a[],char b[],int n)
{
struct node *root;
int i;
if(n==0)
return NULL;
else
{
root = (struct node *)malloc(sizeof(struct node));
root->data=a[n-1];
for(i=0; i<n; i++)
{
if(b[i]==a[n-1])
break;
}
root->lc=creat(a,b,i);//中序后序左子树位置相同
root->rc=creat(a+i,b+i+1,n-i-1);//中序跳过一个根节点
}
return root;
};
int depth(struct node *root)
{
int max,ldepth,rdepth;
if(root==NULL)
max=0;
else
{
ldepth=depth(root->lc);
rdepth=depth(root->rc);
if(ldepth>rdepth)
max=ldepth+1;
else
max=rdepth+1;
}
return max;
}
int main()
{
int n,d;
int t;
scanf("%d",&t);
while(t--)
{
scanf("%s",b);
scanf("%s",a);
int n;
n=strlen(a);
struct node *root;
root=creat(a,b,n);
d=depth(root);
printf("%d\n",d);
}
return 0;
}
来源:https://blog.csdn.net/qq_44427230/article/details/102731069