数据结构实验之二叉树四:还原二叉树
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入
1
个正整数
N(1 <= N <= 50)
为树中结点总数,随后
2
行先后给出先序和中序遍历序列,均是长度为
N
的不包含重复英文字母
(
区分大小写
)
的字符串。
Output
输出一个整数,即该二叉树的高度。
Example Input
9 ABDFGHIEC FDHGIBEAC
Example Output
5
Hint
Author
太长时间没有做,假期做的都忘了,搜了一下网上的答案,博客答案都是一模一样的,由于指针学的不好,就省略了指针,用数组来代替,方法都差不多
还原就是根据两次遍历的数据,找出节点,然后不断递归的过程,深度的计算也是一个递归过程,每次遍历一层加一,取大值,保存回溯,最终最大就是最大深度
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
char data;
struct node * lchild;
struct node * rchild;
};
struct node * creat(int n, char s1[], char s2[])
{
int i;
struct node * root;
if(n == 0)
return NULL;
root = (struct node * )malloc(sizeof(struct node));
root->data = s1[0];
for(i = 0; s2[i] != '\0'; i++)
{
if(s2[i] == s1[0]) //从第一个节点A开始找到每一个节点
break;
}
root->lchild = creat(i, s1 + 1, s2); //根节点的左子树就是第一个节点左边的数据,
root->rchild = creat(n - i - 1, s1 + i + 1, s2 + i + 1); //同理,右边就是右子树,依次递归,把二叉树还原出来
return root;
};
int deep(struct node * root)
{
int d = 0;
if(root) //依次遍历左子树和右子树的,每次递归加一,把最后大的一个存起来
{ //并且返回回来,最后剩下的就是树最大的高度
int d1 = deep(root->lchild);
int d2 = deep(root->rchild);
if(d1 > d2)
d = d1 + 1;
else
d = d2 + 1;
}
return d;
}
int main()
{
int n;
char s1[100], s2[100];
struct node * root;
while(cin >> n)
{
cin >> s1;
cin >> s2;
root = creat(n, s1, s2);
int d = deep(root);
cout << d << endl;
}
return 0;
}