#法创建二叉树,NULL的地方输入‘#’

#define _CRT_SECURE_NO_WARNGINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

typedef struct bintree
{
char c;
struct bintree * lchild;
struct bintree * rchild;
}bintree;


//遍历二叉树
void Recursion(bintree* node)
{
if (node == NULL)
{
return;
}
printf("%c ", node->c);
//先序遍历
Recursion(node->lchild);
//中序遍历
//printf("%c ", node->c);
Recursion(node->rchild);
//后序遍历
//printf("%c ", node->c);
}

bintree *CreateTree()
{
fflush(stdin);
bintree *Tree;
char ch;
scanf("%c", &ch);
if (ch == '#')
Tree = NULL;
else
{
Tree = (bintree *)malloc(sizeof(bintree));
Tree->c = ch;
Tree->lchild = CreateTree();
Tree->rchild = CreateTree();
}
return Tree;
}

//释放二叉树
void ReleaseTree(bintree* node)
{
if (node == NULL)
{
return;
}
ReleaseTree(node->lchild);
ReleaseTree(node->rchild);
free(node);
node = NULL;
}


int main(void)
{
bintree *Tree=CreateTree();
//遍历打印树结点
Recursion(Tree);
//释放二叉树
ReleaseTree(Tree);
system("pause");
return 0;
}

posted on 2016-08-08 23:51  A-祥子  阅读(478)  评论(0)    收藏  举报

导航