题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);
}