PTA 7-1 还原二叉树 (25分)
PTA 7-1 还原二叉树 (25分)
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
【程序思路】
树的建立参考 根据后序和中序遍历输出先序遍历
【程序实现】
#include <bits/stdc++.h>
using namespace std;
struct Tree{
char data;
struct Tree *left;
struct Tree *right;
};
char p1[55],p2[55];
struct Tree *creat(int front1, int rear1, int front2, int rear2) {
struct Tree *root = new struct Tree;
root->data = p1[front1];
root->left = root->right = NULL;
int p = front2;
while(p2[p] != p1[front1])
p++;
int c = p - front2;//左子树节点的个数
if (p != front2) //创建左子树
root->left = creat(front1 + 1 , front1 + c , front2 , p - 1);
if (p != rear2)//创建右子树
root->right = creat(front1 + c + 1 , rear1 , p + 1 , rear2);
return root;
}
int GetHeight( struct Tree *BT ){
int hl,hr;
if(BT) {
hl = GetHeight(BT->left);
hr = GetHeight(BT->right);
return hl > hr ? hl + 1 : hr + 1;
}
return 0;
}
int main()
{
int n;
cin>>n;
getchar();//最后过滤一个回车
scanf("%s",p1);
scanf("%s",p2);
struct Tree *root = creat(0, n - 1, 0, n - 1);
cout<<GetHeight(root)<<endl;
return 0;
}

浙公网安备 33010602011771号