数据结构实验之二叉树四:(先序中序)还原二叉树
Problem Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Sample Input
9
ABDFGHIEC
FDHGIBEAC
Sample Output
5
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
int top,sum;
char a[55],b[55],n;
typedef struct treenode
{
int data;
treenode *l,*r;
}Node;
Node *creat(int len,char *a,char *b)
{
int num;
Node *root;
if(len==0) return NULL;
root=(Node *)malloc(sizeof(Node));
root->data=a[0];
for(int i=0;i<len;i++)
if(b[i]==a[0])
{num=i;break;}
root->l=creat(num,a+1,b);
root->r=creat(len-num-1,a+num+1,b+num+1);
return root;
}
void zhongxu(Node *root)
{
if(root)
{
zhongxu(root->l);
printf("%c",root->data);
zhongxu(root->r);
}
}
void houxu(Node *root)
{
if(root)
{
houxu(root->l);
houxu(root->r);
printf("%c",root->data);
}
}
int deep(Node *root)
{
if(!root) return 0;//到最下面的叶子开始返回
int l=deep(root->l)+1;
int r=deep(root->r)+1;
return max(l,r);
}
int main()
{
Node *root;
while(scanf("%d",&n)!=EOF)
{
scanf("%s%s",a,b);
root=creat(n,a,b);
printf("%d\n",deep(root));
}
return 0;
}
本文介绍了一种通过先序和中序遍历序列还原二叉树,并计算其高度的方法。利用递归创建二叉树节点,再通过深度优先搜索算法计算树的最大高度,最后输出结果。
690

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



