C语言数据结构的简单实验——二叉树的遍历
实验题目:
建立一株用二叉链表储存的二叉树,并对其进行遍历。
实验思路:
解题关键是要建立二叉树,因此对于二叉树的每一个节点,我以链表为储存方式并用递归的思想对其进行定义。
**
代码实现:
**
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
char data;
struct node* Lchild;
struct node* Rchild;
}bitnode;
bitnode* CreatBiNode(); //建立一颗二叉树
void PreOrder(bitnode* node); //先序遍历
void InOrder(bitnode* node); //中序遍历
void PostOrder(bitnode* node); //后序遍历
int main()
{
printf("----------------------二叉树的遍历--------------------------:\n");
bitnode* root = CreatBiNode();
printf("先序遍历:\n");
PreOrder(root);
printf("\n中序遍历:\n");
InOrder(root);
printf("\n后序遍历:\n");
PostOrder(root);
return 0;
}
bitnode *CreatBiNode()
{
bitnode* p;
char ch;
scanf("%c",&ch);
if(ch == ' ')
{
p = NULL;
}
else
{
p = (bitnode*)malloc(sizeof(bitnode));
p->data = ch;
p->Lchild = CreatBiNode();
p->Rchild = CreatBiNode();
}
return p;
}
void PreOrder(bitnode *node)
{
if( node )
{
printf("%c",node->data );
PreOrder(node->Lchild);
PreOrder(node->Rchild);
}
}
void InOrder(bitnode *node)
{
if(node)
{
InOrder(node->Lchild);
printf("%c",node->data);
InOrder(node->Rchild);
}
}
void PostOrder(bitnode *node)
{
if(node)
{
PostOrder(node->Lchild);
PostOrder(node->Rchild);
printf("%c",node->data);
}
}
**
实验结果:
**