SDUT-3343_数据结构实验之二叉树四:(先序中序)还原二叉树

数据结构实验之二叉树四:(先序中序)还原二叉树

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。

Input

输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。

Output

输出一个整数,即该二叉树的高度。

Sample Input

9

ABDFGHIEC

FDHGIBEAC

Sample Output

5

先序中序还原二叉树的方法转至根据先序、中序、后序遍历还原二叉树
题解:
根据先序中序我们可以确认他的左右子树的先序中序
A BDFGHIE C
FDHGIBE A C
还原左子树
BDFGHIE
FDHGIBE
推出
B DFGHI E
FDHGI B E
继续还原
D F GHI
F D HGI
再一次之后D的左子树还原完毕回溯至D还原右子树。、
G H I
H G I
再一次之后D的左右子树还原完毕,回溯至B,还原右子树,这样根节点的左子树还原完毕,右子树还原方式与左子树一致,这里不详述了。
还原之后

/*****************************************/
                        A
            B                       C
    D             E
F       G
      H   I
/****************************************/
#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 front[],char mid[],int n) //利用递归方法建树,n代表字符串的长度
{
    if(n==0)
        return NULL;
    tree *t;
    int i;
    t = newtree();
    t->data = front[0];
    for(i=0;i<n;i++)
        if(mid[i]==front[0])
            break;
    t->l = creat(front+1,mid,i);
    t->r = creat(front+i+1,mid+i+1,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 front[55],mid[55];
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        t = newtree();
        scanf("%s%s",front,mid);
        t = creat(front,mid,n);
        h = 0;
        get_high(t,1);
        //show(t);
        printf("%d\n",h);
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/luoxiaoyi/p/9847642.html
今日推荐