数据结构实验之二叉树四:还原二叉树
Time Limit: 1000MS Memory limit: 65536K
题目描述
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
输入
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
输出
输出一个整数,即该二叉树的高度。
示例输入
9
ABDFGHIEC
FDHGIBEAC
示例输出
5
提示
来源
xam
示例程序
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *lchild,*rchild;
}tree;
tree *creat(char dlr[],char ldr[],int n)
{
tree *root;
char *p;
if(n == 0)
root = NULL;
else
{
root = (tree *)malloc(sizeof(tree));
root->data = dlr[0]; //每次传递过来,首地址存的内容是改变的
for(p = ldr;p != '\0';p++)
if(*p == dlr[0])
break;
int t;
t = p - ldr; //左子树的范围 n-t-1右子树的范围
root->lchild = creat(dlr+1, ldr, t); //传递过去数组的开始
root->rchild = creat(dlr+t+1, p+1, n-(t+1));
}
return root;
}
int depth(tree *root)
{
int h1,h2;
if(!root)
return 0;
else
{
h1 = depth(root->lchild);
h2 = depth(root->rchild);
if(h1 >= h2)
return h1+1;
else
return h2+1;
}
}
int main()
{
int n,k;
tree *root;
char dlr[1000],ldr[1000];
while(~scanf("%d",&n))
{
k = 0;
scanf("%s %s",dlr,ldr);
root = creat(dlr,ldr,n);
k = depth(root);
printf("%d\n",k);
}
return 0;
}
本文介绍了一种通过给定的先序和中序遍历序列来还原二叉树,并计算其高度的方法。利用递归创建二叉树节点,再通过深度优先搜索计算二叉树的最大高度。
422

被折叠的 条评论
为什么被折叠?



