7-23 还原二叉树 (25 分)

方法一:

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

char pre[51],in[51];
int n;
int fun(int t,int low,int high){
    if(low>=high)
        return 1;
    else {
        int mid=0;
        for(int i=low;i<=high;i++){
            if(in[i]==pre[t]){
                mid=i;
                break;
            }
        }
        int h1=fun(t+1,low,mid-1)+1;	//前序序列的t+1号为当前节点的左孩子
        int h2=fun(t+mid-low+1,mid+1,high)+1;	//前序序列的t+mid-low+1号为当前节点的右孩子
        return h1>h2?h1:h2;
    }
}
int main(){
    cin>>n;
    cin>>pre>>in;
    int h=fun(0,0,n-1);
    cout<<h;
    return 0;
}

方法二:

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

typedef struct TNode
{
    char data;
    struct TNode *lchild,*rchild;
} TNode,*Tree;

Tree CreatTree( char xian[],char zhong[],int n);
int High( Tree t);

char xian[55];   //先序序列
char zhong[55];  //中序序列
int n;

int main()
{
    scanf("%d",&n);
    scanf("%s",xian);
    scanf("%s",zhong);
    Tree tree = CreatTree( xian,zhong,n);
    printf("%d",High(tree));
    return 0;
}

Tree CreatTree( char xian[],char zhong[],int n)
{
    if( n==0 ) return NULL;
    int index = 0;
    Tree temp = (Tree) malloc(sizeof(struct TNode));

    while( index < n)
    {
        if( zhong[index]==xian[0]) break;
        index ++;
    }
    temp->data = xian[0];
    temp->lchild = CreatTree(xian+1,zhong,index);
    temp->rchild = CreatTree(xian+1+index,zhong+index+1,n-index-1);
    return temp;
}

int High( Tree t)
{
    if( !t ) return 0;
    int lh = High(t->lchild);
    int rh = High(t->rchild);
    if( lh>rh ) return ++lh;
    else return ++rh;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值