数据结构实验之二叉树八:(中序后序)求二叉树的深度

喜夏-厌秋 提交于 2019-12-02 06:32:24

数据结构实验之二叉树八:(中序后序)求二叉树的深度
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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!