Given a sequence preorder traversal of a binary tree traversal sequence and sequences required to calculate the height of the binary tree.
Input formats:
Firstly, input a positive integer N (≤50), the total number of nodes in the tree points. The next two lines has given preorder traversal sequence and sequence length N are no duplicates letters (case sensitive) string.
Output formats:
Output is an integer, i.e., the height of the binary tree.
Sample input:
9
ABDFGHIEC
FDHGIBEAC
Sample output:
5
Code:
#include<stdio.h>
#include<stdlib.h>
#define MAX 51
typedef char ElementType;
typedef struct node * BinTree;
struct node{
ElementType Data;
BinTree zuo; //左子树
BinTree you; //右子树
};
BinTree Recover(ElementType Pre[MAX],ElementType In[MAX],int len); //建立二叉树
int GetHigh(BinTree T); //计算高度
int main()
{
BinTree Tree;
ElementType xianxu[MAX],zhongxu[MAX];
int N,H;
scanf("%d%s%s",&N,xianxu,zhongxu);
Tree=Recover(xianxu,zhongxu,N);
H=GetHigh(Tree);
printf("%d\n",H);
return 0;
}
BinTree Recover(ElementType Pre[MAX],ElementType In[MAX],int len) //建立二叉树
{
BinTree T;
int i;
if(!len)return NULL; //如果二叉树不存在,则高度为0
else
{
T=(BinTree)malloc(sizeof(struct node));
T->Data=Pre[0]; //根据先序遍历结果确定根结点
for(i=0;i<len;i++) //在中序遍历结果中确定根结点的位置
{
if(Pre[0]==In[i])break;
}
T->zuo=Recover(Pre+1,In,i); //由根结点分,分别建立左子树和右子树
T->you=Recover(Pre+1+i,In+i+1,len-i-1);
}
return T;
}
int GetHigh(BinTree T) //计算高度
{
int l,r,max;
if(T)
{
l=GetHigh(T->zuo);
r=GetHigh(T->you);
max=l>r? l:r;
return max+1;
}
else return 0;
}
}