题目描述
现给定一棵二叉树的先序遍历序列和中序遍历序列,要求你计算该二叉树的高度。
输入格式
输入包含多组测试数据,每组输入首先给出正整数N(<=50),为树中结点总数。下面2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出
对于每组输入,输出一个整数,即该二叉树的高度。
样例输入
9
ABDFGHIEC
FDHGIBEAC
7
Abcdefg
gfedcbA
样例输出
5
7
前几天刚做了一个根据后序和中序来建树的题目,这里是一个前序和中续建树的题目,然后统计树高(408都很熟的算法),直接1A,上篇文章地址:http://blog.csdn.net/iaccepted/article/details/20473661
#include <cstdio>
#include <cstdlib>
#include <queue>
using namespace std;
const int maxx = 52;
typedef struct Tree{
Tree *le;
Tree *ri;
char data;
}Tree;
Tree *root;
char pre[maxx],in[maxx];
int Height(Tree *root,int height){
if(root==NULL)return height;
int lheight = Height(root->le,height+1);
int rheight = Height(root->ri,height+1);
return lheight>rheight?lheight:rheight;
}
Tree *buildTree(int pl,int pr,int il,int ir){
if(pl>pr)return NULL;
int p = il;
while(in[p]!=pre[pl])++p;
Tree *tree = (Tree *)malloc(sizeof(Tree));
tree->data = pre[pl];
tree->le = buildTree(pl+1,pl+p-il,il,p-1);
tree->ri = buildTree(pl+p-il+1,pr,p+1,ir);
return tree;
}
void printPre(Tree *root){
if(root==NULL)return;
printf("%d ",root->data);
printPre(root->le);
printPre(root->ri);
}
int main(){
int n,i,height;
Tree *root;
while(scanf("%d%*c",&n)!=EOF){
for(i=0;i<n;++i){
scanf("%c",&pre[i]);
}
scanf("%*c");
for(i=0;i<n;++i){
scanf("%c",&in[i]);
}
root=buildTree(0,n-1,0,n-1);
height = Height(root,0);
printf("%d\n",height);
}
//printPre(root);
return 0;
}