7-1 还原二叉树 (25分)
给定一棵二叉树的先序遍历序列和中序遍历序列,要求计算该二叉树的高度。
(这个题是已知先序遍历和中序遍历,下面也给出了如果要是已知中序遍历和后序遍历怎样还原二叉树)
输入格式:
输入首先给出正整数N(≤50),为树中结点总数。下面两行先后给出先序和中序遍历序列,均是长度为N的不包含重复英文字母(区别大小写)的字符串。
输出格式:
输出为一个整数,即该二叉树的高度。
输入样例:
9
ABDFGHIEC
FDHGIBEAC
输出样例:
5
分析:
①头文件和结构体的定义:这里选择用单链表的形式进行定义二叉树。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct TNode
{
char data;
struct TNode *lchild,*rchild;
}*Tree;
②根据先序和中序遍历结果来构建这样的一棵二叉树,最后返回根节点,主要就是需要找到两种遍历方式之间的逻辑关系,并利用递归来实现。
Tree CreatTree( char xian[],char zhong[],int n)
{
if( n==0 ) return NULL;
int index = 0;
Tree temp = (struct TNode*) malloc(sizeof(struct TNode));
while( index < n)
{
if( zhong[index]==xian[0]) break;
index ++;
}
temp->data = xian[0];
temp->lchild = CreatTree(xian+1,zhong,index);
temp->rchild = CreatTree(xian+1+index,zhong+index+1,n-index-1);
return temp;
}
③自定义函数来求解一棵固定二叉树的高度,主要就是需要明白二叉树高度的定义——左子树和右子树比较高的一边的高度+1;仍然利用递归来实现。
int High( Tree t)
{
int h1=0,h2=0;
if(t==NULL) return 0;
h1 = High(t->lchild);
h2 = High(t->rchild);
if(h1>h2) return h1+1;
else return h2+1;
}
④主函数以及自定义函数所需变量的定义。
char xian[55];
char zhong[55];
int n;
int main()
{
scanf("%d",&n);
scanf("%s",xian);
scanf("%s",zhong);
Tree tree = CreatTree( xian,zhong,n);
printf("%d",High(tree));
return 0;
}
⑤提交。
7-2 根据后序和中序遍历输出先序遍历 (25分)
本题要求根据给定的一棵二叉树的后序遍历和中序遍历结果,输出该树的先序遍历结果。
输入格式:
第一行给出正整数N(≤30),是树中结点的个数。随后两行,每行给出N个整数,分别对应后序遍历和中序遍历结果,数字间以空格分隔。题目保证输入正确对应一棵二叉树。
输出格式:
在一行中输出Preorder:以及该树的先序遍历结果。数字间有1个空格,行末不得有多余空格。
输入样例:
7
2 3 1 5 7 6 4
1 2 3 4 5 6 7
输出样例:
Preorder: 4 1 3 2 6 5 7
解题思路和上边几乎一样,但要注意输出的给定格式,还有就是输入的是数字,是整数,不是字符,要是写字符的话,会出问题… …
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
typedef struct TNode
{
char data;
struct TNode *lchild,*rchild;
}*Tree;
Tree CreatTree( int hou[],int zhong[],int n)
{
if( n==0 ) return NULL;
int index = 0;
Tree temp = (struct TNode*) malloc(sizeof(struct TNode));
while( index < n)
{
if( zhong[index]==hou[n-1]) break;
index ++;
}
temp->data = hou[n-1];
temp->lchild = CreatTree(hou,zhong,index);
temp->rchild = CreatTree(hou+index,zhong+1+index,n-index-1);
return temp;
}
void Pre(Tree T)
{
if(T==NULL) return;
printf(" %d",T->data);
Pre(T->lchild);
Pre(T->rchild);
}
int hou[55];
int zhong[55];
int n;
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",&hou[i]);
for(int i=0;i<n;i++)
scanf("%d",&zhong[i]);
Tree tree = CreatTree(hou,zhong,n);
printf("Preorder:");
Pre(tree);
return 0;
}
分析就不赘述了,有任何疑惑都可到我公众号(菜菜的学习日记)下给我留言哦,欢迎认真的小伙伴一起和我打卡学习。