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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43545471/article/details/102637333

Problem Description

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

Input

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

Output

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

Sample Input

9
ABDFGHIEC
FDHGIBEAC

Sample Output

5

Hint

Source

xam

建树思路:
1.根据先序序列找到树的根
2.找到根在中序序列的位置
3.在中序序列中划分左右子树,并计算左右子树结点数
4.在先序序列中划分左右子树,并递归治之

求深度思路:
递归求树高

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

#define MaxTree 10

typedef struct Node // 建立树的结点结构
{
    char data;
    struct Node* lchild;
    struct Node* rchild;
}TreeNode;

TreeNode* create_tree(int len, char* pre, char* in) // 递归建树
{
    TreeNode* root = NULL;
    if (len > 0)
    {
        int len_l = 0, len_r = 0;
        root = (TreeNode*)malloc(sizeof(TreeNode));
        root->data = *pre;
        char *p;
        for (p = in; p!=NULL; p++) 遍历中序序列找树根
        {
            if (*p == *pre)
                break;
            len_l++; // 计算左子树结点数
        }
        len_r = len-len_l-1; // 右子树结点数
        root->lchild = create_tree(len_l, pre+1, in); // 递归左子树
        root->rchild = create_tree(len_r, pre+len_l+1, p+1); // 递归右子树
    }
    return root;
}

int PostTreeDepth(TreeNode* root)
{
    int hl, hr, max;
    if (root == NULL) // 递归边界条件
    {
        return 0;
    }
    else
    {
        hl = PostTreeDepth(root->lchild); // 左子树深度
        hr = PostTreeDepth(root->rchild); // 右子树深度
        return hl > hr ? hl+1 : hr+1; // 取最大值
    }
}

int main()
{
    int n;
    char pre[55];
    char in[55];
    TreeNode* root;
    while(~scanf("%d", &n))
    {
        scanf("%s", pre);
        scanf("%s", in);
        root = create_tree(n, pre, in);
        int h = PostTreeDepth(root);
        printf("%d\n", h);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43545471/article/details/102637333