/*求二叉树的结点总数*/
#include<stdio.h>
#define maxsize 100
typedef char datatype;
/*二叉链表类型定义*/
typedef struct Binnode
{
datatype data; /*数据域*/
struct BinNode* lchild,*rchild; /*指向左、右孩子的指针*/
}BinNode,*Bintree;
/*按先序创建二叉树*/
Bintree CreateTree(Bintree T)
{
datatype ch;
scanf("%c",&ch);
if(ch=='#')
return NULL;
else
{
T=(Bintree)malloc(sizeof(BinNode));
T->data=ch;
T->lchild=CreateTree(T->lchild);/*创建左子树*/
T->rchild=CreateTree(T->rchild);/*创建右子树*/
return T;
}
}
/*求二叉树结点总数*/
int Count(Bintree T)
{
if(T==NULL)
return 0; /*空二叉树结点数为0*/
else /*左右子树结点总数加1*/
return Count(T->lchild)+Count(T->rchild)+1;
}
main()
{
Bintree t;
printf("请按先序的方式输入二叉树的结点元素(注:#表示节点为空):");
t=CreateTree(t);
printf("二叉树结点总数:%d",Count(t));
}
求二叉树的结点总数
最新推荐文章于 2025-01-29 22:07:37 发布