#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 20
#define TREESIZE 7
typedef char ElemType;
typedef struct BTNode
{
ElemType data;
struct BTNode *lchild, *rchild;
} BTNode, *BTree;
ElemType pre[MAXSIZE] = { 'a', 'b', 'c', 'e', 'd' };
ElemType in[MAXSIZE] = { 'b', 'c', 'a', 'd', 'e' };
BTNode *GetBTNode();//返回一个二叉树节点
BTNode *GetBTNodeByKey(ElemType key);
BTree CreateBTreeByPreIn(char pre[], char in[], int n);//通过前序中序创建一个二叉树
void PrintArr(ElemType arr[], int n);//输出一个数组
void Visit(BTNode *btnode);//输出某一节点数据
void Preorder(BTree btree); //前序遍历
void Inorder(BTree btree); //中序遍历
void Postorder(BTree btree);//后序遍历
void ShowTree(BTree btree);//静态输出二叉树图形
int main()
{
BTree btree = NULL;
printf("**** 通过二叉树的前序和中序遍历新建一个二叉树 ****\n\n");
printf("输入的前序遍历:"); PrintArr(pre, 5); printf("\n");
printf("输入的中序遍历:"); PrintArr(in, 5); printf("\n");
btree = CreateBTreeByPreIn(pre, in, 5);
printf("\n产生的二叉树:\n");
ShowTree(btree); printf("\n");
printf("该树的后序遍历:"); Postorder(btree); printf("\n");
getchar();
return 0;
}
//通过前序中序创建一个二叉树
BTree CreateBTreeByPreIn(ElemType pre[], ElemType in[], int n)
{
BTree bt = (BTree)GetBTNodeByKey(pre[0]);
int k = 0, i;
for (i = 0; pre[0] != in[i]; i++)
{
k++;
}
// 此时 k 为根节点在中序遍历中的位置的数组下标
if (n == 0)
{
return NULL;
}
else
{
bt->lchild = CreateBTreeByPreIn(pre + 1, in, k);
bt->rchild = CreateBTreeByPreIn(pre + 1 + k, in + k + 1, n - k - 1);
}
return bt;
}
//输出一个数组
void PrintArr(ElemType arr[], int n)
{
int i;
for (i = 0; i < n; i++)
{
printf("%c ", arr[i]);
}
}
void Visit(BTNode *btnode)
{
printf("%c ", btnode->data);
}
BTNode *GetBTNode()
{
BTNode *btnode = (BTNode *)malloc(sizeof(BTNode));
btnode->data = '#';
btnode->lchild = NULL;
btnode->rchild = NULL;
return btnode;
}
BTNode *GetBTNodeByKey(ElemType key)
{
BTNode *btnode = (BTNode *)malloc(sizeof(BTNode));
btnode->data = key;
btnode->lchild = NULL;
btnode->rchild = NULL;
return btnode;
}
void ShowTree(BTree btree)
{
printf(" ");
printf("%c", btree->data);
printf("\n");
printf(" "); printf("%c", btree->lchild->data);
printf(" "); printf("%c", btree->rchild->data);
printf("\n");
if (btree->lchild->lchild != NULL) printf("%c", btree->lchild->lchild->data); else printf(" ");
printf(" ");
if (btree->lchild->rchild != NULL) printf("%c", btree->lchild->rchild->data); else printf(" ");
printf(" ");
if (btree->rchild->lchild != NULL) printf("%c", btree->rchild->lchild->data); else printf(" ");
printf(" ");
if (btree->rchild->rchild != NULL) printf("%c", btree->rchild->rchild->data); else printf(" ");
printf("\n");
}
void Preorder(BTree btree)
{
if (btree != NULL)
{
Visit(btree);
Preorder(btree->lchild);
Preorder(btree->rchild);
}
}
void Inorder(BTree btree)
{
if (btree != NULL)
{
Inorder(btree->lchild);
Visit(btree);
Inorder(btree->rchild);
}
}
void Postorder(BTree btree)
{
if (btree != NULL)
{
Postorder(btree->lchild);
Postorder(btree->rchild);
Visit(btree);
}
}
通过二叉树的前序和中序遍历新建一个二叉树
最新推荐文章于 2022-06-07 18:19:34 发布