#include<stdio.h>
#include<stdlib.h>
typedef struct btnode {
char element;
struct btnode* Lchild, * Rchild;
}BTNode;
typedef struct btree {
struct btnode* Root;
}BTree;
//创建新节点
BTNode* NewNode() {
BTNode* p = (BTNode*)malloc(sizeof(BTNode));
return p;
}
//创建二叉树
void CreateBT(BTree* bt) {
bt->Root = NULL;
}
//将两个二叉树组建为一个二叉树
void MakeBT(BTree* bt, char x, BTree* lt, BTree* rt) {
BTNode* p = NewNode();
p->element = x;
p->Rchild = rt->Root;
p->Lchild = lt->Root;
lt->Root = rt->Root = NULL;
bt->Root = p;
}
void LevelOrd(BTree bt) {
BTNode* p;
BTNode* queue[256];
int front = -1, rear = -1;
p = bt.Root;
rear++;
queue[rear] = p;
while (front != rear) {
front++;
p = queue[front];
printf("%c ", p->element);
if (p->Lchild != NULL) {
rear++;
queue[rear] = p->Lchild;
}
if (p->Rchild != NULL) {
rear++;
queue[rear] = p->Rchild;
}
}
printf("\n");
}
void Visit(BTNode* p) {
printf("%c ", p->element);
}
void PreOrd(void (*Visit)(BTNode* u), BTNode* t) {
if (t) {
(*Visit)(t);
PreOrd(Visit, t->Lchild);
PreOrd(Visit, t->Rchild);
}
}
void InOrd(void (*Visit)(BTNode* u), BTNode* t) {
if (t) {
InOrd(Visit, t->Lchild);
(*Visit)(t);
InOrd(Visit, t->Rchild);
}
}
void PostOrd(void (*Visit)(BTNode* u), BTNode* t) {
if (t) {
PostOrd(Visit, t->Lchild);
PostOrd(Visit, t->Rchild);
(*Visit)(t);
}
}
void PreOrder(BTree* bt, void (*Visit)(BTNode* u)) {
PreOrd(Visit, bt->Root);
}
void InOrder(BTree* bt, void (*Visit)(BTNode* u)) {
InOrd(Visit, bt->Root);
}
void PostOrder(BTree* bt, void (*Visit)(BTNode* u)) {
PostOrd(Visit, bt->Root);
}
//初始化二叉链表结点数组
void InitNodes(BTNode* nodes[], char values[], int size) //size必须是字符数组的总长度
{
int i;
nodes[0] = NewNode();
for (i = 1; i < size; i++)
{
nodes[i] = NewNode();
nodes[i]->element = values[i];
}
}
//根据二叉树的顺序存储结构,生成二叉树的二叉链表结构
BTree* CreateBinaryTree(BTNode* nodes[], int size)
{
BTree* root=(BTree*)malloc(sizeof(BTree));
int i;
if (size < 1)
return NULL;
for (i = 1; i < size; i++)
{
if (2 * i >= size) {
nodes[i]->Lchild = NULL;
nodes[i]->Rchild = NULL;
continue;
}
else {
nodes[i]->Lchild = nodes[2 * i];
}
if (2 * i + 1 >= size) {
nodes[i]->Rchild = NULL;
continue;
}
else {
nodes[i]->Rchild = nodes[2 * i + 1];
}
}
root->Root = nodes[1];
return root;
}
int main() {
char values[] = { ' ', 'A','B','C','D','E','F','G','H' }; //字符数组第一个为空
BTree* root;
BTNode* nodes[256];
//sizeof(values) / sizeof(char) //二叉树的顺序结构的大小
InitNodes(nodes, values, sizeof(values) / sizeof(char));
root = CreateBinaryTree(nodes, sizeof(values) / sizeof(char));
printf( "层次遍历序列:\n");
LevelOrd(*root);
printf("中序遍历序列:\n");
InOrder(root, Visit);
return 0;
}
层次遍历序列:
A B C D E F G H
中序遍历序列:
H D B E A F C G
前序遍历序列:
A B D H E C F G
后序遍历序列:
H D E B F G C A
C:\C++程序&C++PrimerPlus\DataStructrue\HomeWork_6_11_12\Debug\HomeWork_6_11_12.exe (进程 10372)已退出,代码为 0。
要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
按任意键关闭此窗口. . .