一、实验目的
1、掌握二叉树基本概念。
2、掌握二叉树建立方法。
3、掌握二叉树基本操作和遍历方法。
二、实验内容
1、给定一棵二叉树的先序和中序序列,以单个字母表示一个节点,用一个字符串表示的一种序列,构造该二叉树,采用后序遍历,输出后序遍历结果。
2、观察输出结果。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node
{
char data;
struct Node *lchild, *rchild;
}Node, *BiTree;
char PreString[30], InString[30];
BiTree Build(char *PreString, char *InString, int s1, int e1, int s2, int e2)
{
BiTree T = (BiTree)malloc(sizeof(Node));
if(T == NULL)
return 0;
T->data = PreString[s1];
int root;
for(int i = s2; i <= e2; i++) {
if(PreString[s1] == InString[i]) {
root = i;
break;
}
}
int llen = root - s2;
int rlen = e2 - root;
if(llen != 0)
T->lchild = Build(PreString, InString, s1 + 1, s1 + llen, s2, s2 + llen - 1);
else
T->lchild = NULL;
if(rlen != 0)
T->rchild = Build(PreString, InString, e1 - rlen + 1, e1, e2 - rlen + 1, e2);
else
T->rchild = NULL;
return T;
}
void PostOrder(BiTree T)
{
if(T != NULL) {
PostOrder(T->lchild);
PostOrder(T->rchild);
printf("%c", T->data);
}
}
int main()
{
BiTree T1;
printf("Input the pre order sequence of the strings:");
scanf("%s", PreString);
printf("Input the in order sequence of the strings:");
scanf("%s", InString);
T1 = Build(PreString, InString, 0, strlen(PreString) - 1, 0, strlen(InString) - 1);
printf("The post order sequence of the strings are:");
PostOrder(T1);
printf("\n");
return 0;
}