标题根据中序序列和后序序列确定二叉树
一些基本的函数和初始化
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
char data;
struct Node* lchild;
struct Node* rchild;
}Node ,*Root;
主函数
int main()
{
Root BT;
BT=union_pre_and_in();
print_pre_order(BT);
printf("\n");
print_in_order(BT);
printf("\n");
print_post_order(BT);
printf("\n");
print_level_order(BT);
printf("\n");
}
输入结点个数以及二叉树的中序和后序序列
Node* union_pre_and_in()
{
Node* BT;
char in[1000], post[1000];
int k;
printf("请输入结点个数:");
scanf("%d", &k);
scanf("%s", in);
scanf("%s", post);
BT=pre_and_in_create(in,post,k);
return BT;
}
创建二叉树
Node* pre_and_in_create(char* in, char* post, int k)
{
if (k > 0)
{
Node* BT = (Node*)malloc(sizeof(Node));
char* edge = in;
char* root_position = post + k - 1;
BT->data = *root_position;
while (*edge != *root_position)
{
edge++;
}
BT->lchild = pre_and_in_create(in, post, edge - in);
BT->rchild = pre_and_in_create(edge + 1, post + (edge - in), k - 1 - (edge - in));
return BT;
}
else
return NULL;
}
源代码
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
char data;
struct Node* lchild;
struct Node* rchild;
}Node, * Root;
Node* queue[1000];
int rear = -1, front = -1;
void pre_order_create(Root* BT)
{
*BT = (Root)malloc(sizeof(Node));
char ch;
scanf("%c", &ch);
if (ch != '#')
{
(*BT)->data = ch;
pre_order_create(&((*BT)->lchild));
pre_order_create(&((*BT)->rchild));
}
else
{
*BT = NULL;
}
}
void print_pre_order(Root BT)
{
if (BT)
{
printf("%c", BT->data);
print_pre_order(BT->lchild);
print_pre_order(BT->rchild);
}
}
void print_in_order(Root BT)
{
if (BT)
{
print_in_order(BT->lchild);
printf("%c", BT->data);
print_in_order(BT->rchild);
}
}
void print_post_order(Root BT)
{
if (BT)
{
print_post_order(BT->lchild);
print_post_order(BT->rchild);
printf("%c", BT->data);
}
}
void print_level_order(Root BT)
{
Node* temp;
if (BT)
{
queue[++rear] = BT;
while (front != rear)
{
temp = queue[++front];
printf("%c", temp->data);
if (temp->lchild) queue[++rear] = temp->lchild;
if (temp->rchild) queue[++rear] = temp->rchild;
}
}
}
Node* pre_and_in_create(char* in, char* post, int k)
{
if (k > 0)
{
Node* BT = (Node*)malloc(sizeof(Node));
char* edge = in;
char* root_position = post + k - 1;
BT->data = *root_position;
while (*edge != *root_position)
{
edge++;
}
BT->lchild = pre_and_in_create(in, post, edge - in);
BT->rchild = pre_and_in_create(edge + 1, post + (edge - in), k - 1 - (edge - in));
return BT;
}
else
return NULL;
}
Node* union_pre_and_in()
{
Node* BT;
char in[1000], post[1000];
int k;
printf("请输入结点个数:");
scanf("%d", &k);
printf("请输入中序序列:");
scanf("%s", in);
printf("请输入后序序列:");
scanf("%s", post);
BT = pre_and_in_create(in, post, k);
return BT;
}
int main()
{
Root BT;
BT = union_pre_and_in();
printf("前序遍历为:");
print_pre_order(BT);
printf("\n");
printf("中序遍历为:");
print_in_order(BT);
printf("\n");
printf("后序遍历为:");
print_post_order(BT);
printf("\n");
printf("层次遍历为:");
print_level_order(BT);
printf("\n");
}