#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
typedef struct BiNode
{
int data;
struct BiNode *lchild,*rchild;
} BiNode;
void Preorder(BiNode *root);
BiNode *CreatBiTree(BiNode *root);
void DestoryBiTree(BiNode *root);
int main()
{
char a[100];
BiNode *root = NULL;
root = CreatBiTree(root);
printf("该二叉树的结点是%c\n",root->data);
printf("\n该二叉树的前序遍历序列是:");
Preorder(root);
printf("\n该二叉树的中序遍历序列是:");
InOrder(root);
printf("\n该二叉树的后序遍历序列是:");
PostOrder(root);
DestoryBiTree(root);
return 0;
}
//前序遍历
void Preorder(BiNode *root)
{
if(root == NULL)
return ;
else
{
printf("%c",root->data);
Preorder(root->lchild);
Preorder(root->rchild);
}
}
//中序遍历
void InOrder(BiNode *root)
{
if(root == NULL)
return ;
else
{
InOrder(root->lchild);
printf("%c",root->data);
InOrder(root->rchild);
}
}
//后序遍历
void PostOrder(BiNode *root)
{
if( root == NULL)
return ;
else
{
PostOrder(root->lchild);
PostOrder(root->rchild);
printf("%c",root->data);
}
}
//建立二叉链表
BiNode *CreatBiTree(BiNode *root)
{
char ch;
printf("请输入数据以 # 结束\n");
scanf("%c",&ch);
getchar();//吃回车
if(ch == '#')
root = NULL;
else
{
root = (BiNode *)malloc(sizeof(BiNode));
root->data = ch;
root->lchild = CreatBiTree(root->lchild);
root->rchild = CreatBiTree(root->rchild);
}
return root;
}
//销毁链表
void DestoryBiTree(BiNode *root)
{
if(root == NULL)
return ;
DestoryBiTree(root->lchild);
DestoryBiTree(root->rchild);
}
二叉树的三种遍历方式-链表实现
猜你喜欢
转载自blog.csdn.net/CSDNsabo/article/details/91948175
今日推荐
周排行