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

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

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

Input

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

Output

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

Sample Input

9 
ABDFGHIEC
FDHGIBEAC

Sample Output

5

Hint

Source

xam\

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

char pre[55];
char mid[55];

struct node
{
    char data;
    struct node *left;
    struct node *right;
};

struct node *creat(char *pre, char *mid, int n)
{
    if(n <= 0) return NULL;
    int k;
    struct node *root;
    root = (struct node *)malloc(sizeof(struct node));
    root -> data = *pre;
    for(k = 0; k < n; k++)
    {
        if(mid[k] == pre[0])
            break;
    }
    root -> left = creat(pre + 1, mid, k);
    root -> right = creat(pre + k + 1, mid + k + 1, n - k - 1);
    return root;
};

int height(struct node *root)              // 递归求高度
{
    if(root)
    {
        int m = height(root -> left);
        int n = height(root -> right);
        return (m > n)?(m + 1):(n + 1);
    }
    else
        return 0;
}

int main()
{
    int h;
    int n;
    while(~scanf("%d", &n))
    {
        scanf("%s", pre);
        scanf("%s", mid);
        struct node *root;
        root = creat(pre, mid, n);
        h = height(root);
        printf("%d\n", h);
    }
    return 0;
}
 

猜你喜欢

转载自blog.csdn.net/strongerXiao/article/details/81502997
今日推荐