数据结构实验之二叉树四:(先序中序)还原二叉树
来源:互联网 发布:手机广告设计软件 编辑:程序博客网 时间:2024/05/22 14:13
Problem Description
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
Input
输入数据有多组,每组数据第一行输入1个正整数N(1 <= N <= 50)为树中结点总数,随后2行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区分大小写)的字符串。
Output
输出一个整数,即该二叉树的高度。
Example Input
9 ABDFGHIECFDHGIBEAC
Example Output
5
code:
#include<stdio.h>
#include<stdlib.h>
typedef struct Bitnode
{
char data;
struct Bitnode *lchild, *rchild;
}Bitree;
Bitree *rebuild(char *a, char *b, int n)
{
Bitree *T;
int i;
if(n==0) return NULL;
T = (Bitree*)malloc(sizeof(Bitree));
T->data = a[0];//因为a为前序的序列,故a[0]本就是根节点;
for(i = 0;i<n;i++)//找到中序中第一个和前序相等的元素此时的i指向在a元素中T的右支点的前一个
{
if(b[i] == a[0]) break;
}
T->lchild = rebuild(a+1, b, i);//让向后移动一个,此时的a[0]向后移动,恰好为左支点;
T->rchild = rebuild(a+i+1, b+i+1, n-i-1);//使a与b同时后移i+1个元素,让a指向右结点,不断递归获得原始的树;
return T;
}
int max(int a, int b)
{
if(a>b) return a;
else return b;
}
int hight(Bitree *root)
{
if(root==NULL) return 0;
else return max(hight(root->lchild), hight(root->rchild))+1;
}
int main()
{
int t;
char a[51];
char b[51];
while(~scanf("%d", &t))
{
scanf("%s", a);
scanf("%s", b);
Bitree *T;
T = rebuild(a, b, t);
int hi = hight(T);
printf("%d\n", hi);
}
}
#include<stdlib.h>
typedef struct Bitnode
{
char data;
struct Bitnode *lchild, *rchild;
}Bitree;
Bitree *rebuild(char *a, char *b, int n)
{
Bitree *T;
int i;
if(n==0) return NULL;
T = (Bitree*)malloc(sizeof(Bitree));
T->data = a[0];//因为a为前序的序列,故a[0]本就是根节点;
for(i = 0;i<n;i++)//找到中序中第一个和前序相等的元素此时的i指向在a元素中T的右支点的前一个
{
if(b[i] == a[0]) break;
}
T->lchild = rebuild(a+1, b, i);//让向后移动一个,此时的a[0]向后移动,恰好为左支点;
T->rchild = rebuild(a+i+1, b+i+1, n-i-1);//使a与b同时后移i+1个元素,让a指向右结点,不断递归获得原始的树;
return T;
}
int max(int a, int b)
{
if(a>b) return a;
else return b;
}
int hight(Bitree *root)
{
if(root==NULL) return 0;
else return max(hight(root->lchild), hight(root->rchild))+1;
}
int main()
{
int t;
char a[51];
char b[51];
while(~scanf("%d", &t))
{
scanf("%s", a);
scanf("%s", b);
Bitree *T;
T = rebuild(a, b, t);
int hi = hight(T);
printf("%d\n", hi);
}
}
阅读全文
0 0
- 数据结构实验之二叉树四:(先序中序)还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- SDUT3343数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- SDUT3343数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- 数据结构实验之二叉树四:还原二叉树
- Inno Setup入门(四)——为程序创建桌面快捷方式
- Java 静态导入
- 会话技术
- 51nod 1557 两个集合 (严谨的逻辑题)
- 彻底搞懂Websocket原理
- 数据结构实验之二叉树四:(先序中序)还原二叉树
- 大数据基础设施建设需要得到重视 | 记清华大数据“应用·创新”讲座
- [agc006e]Rotate 3x3
- 常见七种排序算法
- GhostScript命令参数详解
- 如何处理前任程序员留下的代码
- Mybatis 调试 range for the datatype
- ESP8266编译脚本之三
- C++ 中矩阵运算的实现