7-23 還原二叉樹 (25分) 【PTA 先序 + 中序 求 高度】

7-23 還原二叉樹 (25分)

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

輸入格式:

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

輸出格式:

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

輸入樣例:

9
ABDFGHIEC
FDHGIBEAC

輸出樣例:

5

 

#include <iostream>
#include<bits/stdc++.h>

using namespace std;
struct node
{
    char data;
    struct node *lc,*rc;
};
char s[1000];
char t[1000];
int n;
struct node *create(int len, char a[], char b[])
{
    if(len == 0) return NULL;
    int i;
    struct node *root;
    root = new node;
    root -> data = a[0];
    for(i = 0; i < len; i ++)
    {
        if(a[0] == b[i])
        {
            break;
        }
    }
    root -> lc = create(i,a+1,b);
    root -> rc = create(len - i - 1, a + i + 1, b + i + 1);
    return root;
};

int fin(struct node * root)
{
    int d1,d2;
    int h = 0;
    if(root)
    {
        d1 = fin(root -> lc);
        d2 = fin(root -> rc);
        h = max(d1+1,d2+1);
    }
    return h;
}
int main()
{
//    int n;
    scanf("%d", &n);
    scanf("%s %s",s,t);
    struct node *root;;
    root = create(n,s,t);
    int ans = fin(root);
    printf("%d\n",ans);
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章