编写程序实现二叉树的创建,三种遍历自己销毁
#include <myhead.h>
//树结点
typedef struct Node
{
char data;
struct Node* lchild;
struct Node* rchild;
}*Btree;
//结点创建
Btree create_node()
{
Btree t=(Btree)malloc(sizeof(struct Node));
if(NULL ==t)
return NULL;
t->data=0;
t->lchild=t->rchild=NULL;
return t;
}
//二叉树创建
Btree create_tree()
{
char element;
printf("请输入字符:");
scanf("%c",&element);
getchar();
if(element == '#')
return NULL;
Btree tree = create_node();
tree->data = element;
tree->lchild = create_tree();
tree->rchild = create_tree();
return tree;
}
//先序
void first_output(Btree tree)
{
if(NULL == tree)
return;
printf("%c",tree->data);
first_output(tree->lchild);
first_output(tree->rchild);
}
//中序
void mid_output(Btree tree)
{
if(NULL == tree)
return;
mid_output(tree->lchild);
printf("%c",tree->data);
mid_output(tree->rchild);
}
//后序
void last_output(Btree tree)
{
if(NULL == tree)
return;
last_output(tree->lchild);
last_output(tree->rchild);
printf("%c",tree->data);
}
//释放
Btree free_space(Btree tree)
{
if(NULL ==tree)
return NULL;
free_space(tree->lchild);
free_space(tree->rchild);
free(tree);
tree=NULL;
}
int main(int argc, const char *argv[])
{
Btree tree = NULL;
tree = create_tree();
printf("先序遍历:");
first_output(tree);
printf("\n中序遍历:");
mid_output(tree);
printf("\n后序遍历:");
last_output(tree);
printf("\n");
//释放
free_space(tree);
return 0;
}