数据结构实验之二叉树四:还原二叉树
Time Limit: 1000MS Memory limit: 65536K
题目描述
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
输出
输出一个整数,即该二叉树的高度。
示例输入
9
ABDFGHIEC
FDHGIBEAC
示例输出
5
提示
根据一颗二叉树的中序遍历和后序遍历或中序遍历和前序遍历都可以确定唯一的一颗二叉树。
例子:ABCDEFG
CBDAEGF
首先根据先序序列可知,二叉树的根节点为A,其次根据A在序列中的位置,将中序序列分为两部分,A左边部分 CBD为A的左子树的节点,A右边部分EGF为A的右子树的结点。对于左子树,先序序列为BCD,从而得知,左子
树的根节点为B,再由对应的中序序列可知,B的左子树结点为C,右子树的结点为D。对A的右子树采用同样的办法
进行处理,对E的右子树继续分解,最终得到如图所示的二叉树。
坐标定位:
<span style="font-size:18px;">#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef char ElemType;
typedef struct BiTNode
{
char data;
struct BiTNode *lchild,*rchild;
} BiTNode,*BiTree;
char a[100];
BiTree PreInOrder(char preord[],char inord[],int i,int j,int k,int h)
{
int m;
BiTree T;
if (j<0||h<0)
T = NULL;
else
{
T = (BiTree)malloc (sizeof (BiTNode));
T->data = preord[i];
m = k;
while (inord[m] != preord[i])
m++;
if (m==k)
T->lchild = NULL;
else T->lchild = PreInOrder(preord,inord,i+1,i+m-k,k,m-1);
if (m==h)
T->rchild = NULL;
else T->rchild = PreInOrder(preord,inord,i+m-k+1,j,m+1,h);
}
return T;
}
int Depth(BiTree T)
{
int depthval;
if (!T)
depthval = 0;
else
{
int depthLeft = Depth(T->lchild);
int depthRight = Depth(T->rchild);
depthval = 1+(depthLeft > depthRight ? depthLeft : depthRight);
}
return depthval;
}
int main()
{
int t,n;
BiTree T;
char preord[100],inord[100];
while (~scanf ("%d",&n))
{
scanf ("%s",preord);
scanf ("%s",inord);
T = PreInOrder(preord,inord,0,n-1,0,n-1);
int k = Depth(T);
printf ("%d\n",k);
}
return 0;
}
</span>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct node
{
char data;
struct node *lchild,*rchild;
};
struct node *Build(struct node *T,char *preord,char *inord,int n)
{
if (n<=0)
return NULL;
else
{
T = (struct node *)malloc (sizeof (struct node));
T->data = preord[0];
int k = strchr(inord,preord[0])-inord;//定位函数,查找字符串s中首次出现字符c的位置。
T->lchild = Build(T->lchild,preord+1,inord,k);
T->rchild = Build(T->rchild,preord+k+1,inord+k+1,n-k-1);
}
return T;
}
int Depth(struct node *T)
{
int d = 0,depthL,depthR;
if(T==NULL)
return 0;
if (T->lchild == NULL && T->rchild == NULL)
return 1;
depthL = Depth(T->lchild);
depthR = Depth(T->rchild);
d = 1+(depthL > depthR ? depthL : depthR);
return d;
}
int main()
{
int n;
while (~scanf ("%d%*c",&n))
{
char preord[100],inord[100];
struct node *root;
scanf ("%s",preord);
scanf ("%s",inord);
root = Build(root,preord,inord,n);
int d = Depth(root);
printf ("%d\n",d);
}
return 0;
}