#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define maxn 55
char pre[maxn];
char in[maxn];
typedef struct node
{
char ch;
struct node *left, *right;
}node, *Node;
int i;
Node create(int l, int r)// l r 表示该树在中序中的范围
{
int j, mid;
if(l > r)
{
return NULL; // 空树
}
Node tmp = (Node)malloc(sizeof(node));
tmp->ch = pre[i];
for(j = l;j <= r;j++)// 找到根 在中序中的位置
{
if(pre[i] == in[j])
{
mid = j;
break;
}
}
i++;
tmp->left = create(l, mid-1);
tmp->right = create(mid+1, r);
return tmp;
}
int max(int x, int y)
{
return x > y?x:y;
}
int height(Node T)
{
if(T == NULL)return 0;//如果时空树 高度为0
return max(height(T->left), height(T->right))+1;// 否则等于子树中最高的那个+1
}
int main()
{
int n;
while(~scanf("%d", &n))
{
scanf("%s", pre);
scanf("%s", in);
i = 0;
Node root = NULL;
root = create(0, n-1);
int h = height(root);
printf("%d\n", h);
}
return 0;
}
数据结构实验之二叉树四:(先序中序)还原二叉树————SDUT
最新推荐文章于 2020-10-30 17:22:51 发布