#include<stdio.h>
#include<stdlib.h>
typedef struct tree //定义二叉树的结构
{
char data;
struct tree *lchild;
struct tree *rchild;
}BinTree;
/*
**创建二叉树
*/
void CreateTree(BinTree *&pBtree)
{
char c;
scanf("%c",&c);
if(c=='@') //子树的结束标识符
{
pBtree=NULL;
}
else
{
pBtree=(BinTree *)malloc(sizeof(BinTree));
if(pBtree==NULL)
{
printf("malloc使用失败!\n");
exit(0);
}
pBtree->data=c;
CreateTree(pBtree->lchild); //继续递归去建立左右二叉子树
CreateTree(pBtree->rchild);
}
}
/*
**先序遍历二叉树
*/
void FirstTraverse(BinTree *&pBtree)
{
if(pBtree==NULL)
return;
printf("%c",pBtree->data);
FirstTraverse(pBtree->lchild);
FirstTraverse(pBtree->rchild);
}
/*
**求节点的总数
*/
int sumNode(BinTree *&pBtree)
{
int sum=0;
if(pBtree==NULL)
return 0;
sum++;
sum+=sumNode(pBtree->lchild);
sum+=sumNode(pBtree->rchild);
return sum;
}
/*
**销毁二叉树
*/
void DestroyTree(BinTree *&pBtree)
{
if(pBtree==NULL)
return;
DestroyTree(pBtree->lchild);
DestroyTree(pBtree->rchild);
free(pBtree);
}
int main()
{
BinTree *pBtree;
printf("请输入二叉树的节点:\n");
CreateTree(pBtree);
printf("二叉树的先序遍历:\n");
FirstTraverse(pBtree);
printf("\n节点总数是:\n");
printf("%d\n",sumNode(pBtree));
DestroyTree(pBtree);
return 0;
}