数据结构实验之二叉树四:(先序中序)还原二叉树
Time Limit: 1000 ms
Memory Limit: 65536 KiB
Problem Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Sample Input
9 ABDFGHIEC FDHGIBEAC
Sample Output
5
#include <stdio.h> #include <stdlib.h> #include <string.h> struct node { int data; char c; struct node *lt, *rt; }; char s1[100],s2[100]; struct node *creat(int n, char s1[], char s2[]) { int i=0; struct node *root; if(n==0) return NULL; root=(struct node *)malloc(sizeof(struct node)); root->c=s1[0]; for(i=0; i<n; i++){ if(s1[0]==s2[i]){ root->lt=creat(i, s1+1, s2); root->rt=creat(n-i-1, s1+i+1, s2+i+1); } } return root; } /*void fir(struct node *root) { if(root){ printf("%c",root->c); fir(root->lt); fir(root->rt); } }*/ int h(struct node *root) { if(root->lt==NULL&&root->rt==NULL){ root->data=1; } else if(root->lt==NULL&&root->rt!=NULL){ root->data=h(root->rt)+1; } else if(root->lt!=NULL&&root->rt==NULL){ root->data=h(root->lt)+1; } else if(root->lt!=NULL&&root->rt!=NULL){ if(h(root->lt)>h(root->rt)){ root->data=h(root->lt)+1; } else{ root->data=h(root->rt)+1; } } return root->data; } int main() { int n; while(~scanf("%d",&n)){ scanf("%s %s",s1,s2); struct node *root; root=creat(n,s1,s2); //fir(root); printf("%d\n",h(root)); } return 0; }