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

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

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

中序后序还原二叉树的方法转至根据先序、中序、后序遍历还原二叉树

以样例一为例:
先以中序后序确定左右子树的中序后序
dbge a fc
dgeb fc a
还原左子树
dbge
dgeb
推出
d b ge
d ge b
还原左子树,d的左右儿子为空,回溯b,还原右子树
g e
g e
还原e的左子树,右子树为空,回溯到b,b的左右子树还原完毕,回溯到根节点,还原右子树。
右子树还原与左子树还原方法一致,不再详述。

  • 还原的树
/*******************************/
            a
    b               c
d       e         f
      g  
/*******************************/

可以看出最深为a-b-e-g


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct tree
{
    char data;
    struct tree *l,*r;
}tree;

tree *newtree()
{
    tree *t;
    t = (tree*)malloc(sizeof(tree));
    t->l = t->r = NULL;
    return t;
}

int h;

tree *creat(char mid[],char back[],int n)
{
    if(n==0)
        return NULL;
    tree *t;
    int i;
    t = newtree();
    t->data = back[n-1];
    for(i=0;i<n;i++)
        if(mid[i]==back[n-1])
            break;
    t->l = creat(mid,back,i);
    t->r = creat(mid+i+1,back+i,n-i-1);
    return t;
}

void get_high(tree *t,int i)
{
    if(t)
    {
        if(h<i)
            h = i;
        get_high(t->l,i+1);
        get_high(t->r,i+1);
    }
}

void show(tree *t)
{
    if(t)
    {
        printf("%c",t->data);
        show(t->l);
        show(t->r);
    }
}

int main()
{
    tree *t;
    char back[55],mid[55];
    int n,k;
    while(scanf("%d",&k)!=EOF)
    {
        while(k--)
        {
            t = newtree();
            scanf("%s%s",mid,back);
            n = strlen(mid);
            t = creat(mid,back,n);
            h = 0;
            get_high(t,1);
            //show(t);
            printf("%d
",h);
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/luoxiaoyi/p/9848695.html