1. 程式人生 > >資料結構實驗之二叉樹八:(中序後序)求二叉樹的深度

資料結構實驗之二叉樹八:(中序後序)求二叉樹的深度

Problem Description

已知一顆二叉樹的中序遍歷序列和後序遍歷序列,求二叉樹的深度。

Input

輸入資料有多組,輸入T,代表有T組資料。每組資料包括兩個長度小於50的字串,第一個字串表示二叉樹的中序遍歷,第二個表示二叉樹的後序遍歷。

Output

輸出二叉樹的深度。

Sample Input

2
dbgeafc
dgebfca
lnixu
linux

Sample Output

4
3
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct no
{
    int data;
    struct no *lc,*rc;
}node;
int max;
node *creat(int len,char mid[],char end[])
{
    node *root;
    int i;
    if(len==0)
        return NULL;
    for(i=0;i<len;i++)
    {
        if(end[len-1]==mid[i])
            break;
    }
    root=(node *)malloc(sizeof(node));
    root->data=mid[i];
    root->lc=creat(i,mid,end);
    root->rc=creat(len-i-1,mid+i+1,end+i);
    return root;
}
void deep(node *root,int c)
{
    if(root)
    {
       deep(root->lc,c+1);
        deep(root->rc,c+1);
        if(c>max)max=c;
    }
}
int main()
{
    int t;
    node *root;
    char mid[60],end[60];
    scanf("%d",&t);
    while(t--)
    {
        scanf("%s %s",mid,end);
        root=creat(strlen(mid),mid,end);
        max=0;
        deep(root,1);
        printf("%d\n",max);
    }
    return 0;
}