1. 程式人生 > >還原二叉樹 (C語言)

還原二叉樹 (C語言)

題目描述

給定一棵二叉樹的先序遍歷序列和中序遍歷序列,要求計算該二叉樹的高度。

輸入描述

輸入首先給出正整數N(≤50),為樹中結點總數。下面兩行先後給出先序和中序遍歷序列,均是長度為N的不包含重複英文字母(區別大小寫)的字串。

輸出描述

輸出為一個整數,即該二叉樹的高度。

輸入樣例
9
ABDFGHIEC
FDHGIBEAC

輸出樣例
5


//這題就是直接用之前通過中序和前序找後序的程式碼直接改的,就是把輸出後序改成了計算高度
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

typedef struct Node
{
    char data;
    struct Node *lchild;
    struct Node *rchild;
}List;

int h, max;
char pre[30], in[30];

//當前先序序列的區間為[preL, preR], 中序序列區間為[inL, inR],返回根節點的地址
List* Create(int preL, int preR, int inL, int inR)
{
    if(preL > preR)
    {
        return NULL; //先序序列長度小於等於0時,直接返回
    }
    List *root = (List *)malloc(sizeof(List));
    root->data = pre[preL];
    int k;
    for(k = inL; k <= inR; k++)
    {
        if(in[k] == pre[preL]) //在中序序列中找到in[k] == pre[preL]的結點
        {
            break;
        }
    }
    int numLeft = k - inL; //對於當前結點的左子樹的結點的個數
    root->lchild = Create(preL+1, preL+numLeft, inL, k-1);
    root->rchild = Create(preL+numLeft+1, preR, k+1, inR);

    return root; //返回根結點地址
}

void Postorder(List *root, int k)
{
    if(root != NULL)
    {
        if(k > max)
            max = k;
       Postorder(root->lchild, k+1);
       Postorder(root->rchild, k+1);
    }


}

int main()
{
    int n;
    while(~scanf("%d", &n))
    {
        scanf("%s", pre);
        scanf("%s", in);
        h = strlen(pre);
        max = 0;
        List *root = Create(0, h-1, 0, h-1); //建樹
        Postorder(root, 1);
        printf("%d\n", max);
    }
    return 0;
}