题34.pta数据结构题集-7-23 还原二叉树 (25 分)


题34.pta数据结构题集-7-23 还原二叉树 (25 分)


一、题目

在这里插入图片描述

二、题解

本题的关键在于通过前中序遍历序列建立二叉树,然后改造后序遍历来计算树的高度

#include <bits/stdc++.h>

using namespace std;

char pre[50],in[50];
int N;

typedef struct Tnode *Position;
typedef Position BinT;
struct Tnode
{
    char data;
    BinT left;
    BinT right;
};

BinT Create_Tree(int front_pos,int last_pos)
{
    BinT T=(BinT)malloc(sizeof(struct Tnode));
    int i,j;
    int flag=0;
    for(i=0; i<N; i++)
    {

        for(j=front_pos; j<last_pos; j++)
        {
            if(pre[i]==in[j])
            {
                flag=1;
                break;
            }
        }
        if(flag==1)
        {
            break;
        }
    }
    T->data=in[j];
    if(front_pos==j)//左子树为空
    {
        T->left=NULL;
    }
    else
    {
        T->left=Create_Tree(front_pos,j);
    }
    if(last_pos-1==j)//右子树为空
    {
        T->right=NULL;
    }
    else
    {
        T->right=Create_Tree(j+1,last_pos);
    }
    return T;
}

int PostOrderGetHeight(BinT BT)
{
    BinT T;
    int HL,HR,MaxH;
    T=BT;
    if(T)
    {
        HL=PostOrderGetHeight(T->left);//递归去计算左子树高度
        HR=PostOrderGetHeight(T->right);//递归去计算右子树高度
        //cout<<T->data<<endl;
        //取最大为该子树的高度
        if(HL>HR)
        {
            MaxH=HL;
        }
        else
        {
            MaxH=HR;
        }
        return MaxH+1;//这个+1很重要
    }
    else//若子树为空则高度为0
    {
        return 0;
    }
}

int main()
{
    BinT T;
    cin>>N;
    for(int i=0; i<N; i++)
    {
        cin>>pre[i];
    }
    for(int i=0; i<N; i++)
    {
        cin>>in[i];
    }
    T=Create_Tree(0,N);
    cout<<PostOrderGetHeight(T);
    free(T);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值