二叉树是一种很常用的数据结构,由于树的定义是递归的,二叉树只是一种特殊的树,所以二叉树的定义也是递归的,因此二叉树的建立和遍历自然也要使用递归思想。
#include <stdio.h>
#include <stdlib.h>
typedef struct BTNode *BTptr;
typedef struct BTNode {
char data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTree;
void create_tree(BTptr *T)
{
char c;
scanf("%c",&c);
if('#' == c)
{
*T = NULL;
return;
}
*T = (BTptr)malloc(sizeof(BTree));
if(*T == NULL)
{
printf("Error: no memory to alloc in system!!\n");
return;
}
(*T)->data = c;
create_tree(&((*T)->lchild));
create_tree(&((*T)->rchild));
}
void print_preorder(BTptr T)
{
if(T == NULL)
return;
printf("\t%c\t",T->data);
print_preorder(T->lchild);
print_preorder(T->rchild);
}
void print_inorder(BTptr T)
{
if(T == NULL)
return;
print_inorder(T->lchild);
printf("\t%c\t",T->data);
print_inorder(T->rchild);
}
void print_postorder(BTptr T)
{
if(T == NULL)
return;
print_postorder(T->lchild);
print_postorder(T->rchild);
printf("\t%c\t",T->data);
}
int main(void)
{
BTptr T;
create_tree(&T);
printf("当前树的前序遍历为:");
print_preorder(T);
printf("\n");
printf("当前树的中序遍历为:");
print_inorder(T);
printf("\n");
printf("当前树的后序遍历为:");
print_postorder(T);
printf("\n");
return 0;
}