给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
解答:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct TNode{
char data;
struct TNode *lchild,*rchild;
} TNode,* Tree;
Tree CreatTree( char Pre[],char Mid[],int n);
int High( Tree t);
char Pre[55]; //先序序列
char Mid[55]; //中序序列
int n;
int main(){
scanf("%d",&n);
scanf("%s",Pre);
scanf("%s",Mid);
Tree tree = CreatTree( Pre,Mid,n);
printf("%d",High(tree));
return 0;
}
Tree CreatTree( char Pre[],char Mid[],int n){
if( n==0 )
return NULL;
int index = 0;
Tree root = (Tree) malloc(sizeof(struct TNode));
while( index < n){
//寻找当前父亲节点在中序遍历的位置
if( Mid[index]==Pre[0])
break;
index ++;
}
root->data = Pre[0];
//--------------------------左孩子节点一定在中序序列中父亲节点的左边------------------------
//Pre+1 左孩子节点在其Pre+1的数组中(摒弃父亲节点元素的数组)
//Mid 左孩子节点一定在中序序列的开头到父亲节点之间
//index 左孩子的个数及其位置不会超过index ----------------------------------------------
root->lchild = CreatTree(Pre+1,Mid,index); // |
// |
//--------------------------右孩子节点一定在中序序列中父亲节点的右边------------------// |-->注意,其中Mid和Pre都是从0开始判断,该式有效控制数组序列一定有效
//Pre+1+index 右孩子节点在其Pre+1+index的数组中(摒弃左孩子元素和父亲节点元素的数组) // |
//Mid+index+1 右孩子节点在的位置一定在父亲节点的右边 // |
//n-index-1 == n-(index+1) 表示右孩子的个数及其位置不会超过n-index-1----------------------
root->rchild = CreatTree(Pre+1+index,Mid+index+1,n-index-1);
return root;
}
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;
}