利用二叉树创建、遍历算法,编写程序,创建一颗二叉树,求二叉树中总结点数和叶子结点数。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct Tnode{
char Data;
struct Tnode *Left,*Right;
}Btree,*BinTree;
void CreateBinTree(BinTree *BT)//先序创建二叉树
{
char ch;
scanf("%c",&ch);
if(ch=='#') *BT=NULL;
else{
*BT=(BinTree)malloc(sizeof(Btree));
(*BT)->Data=ch;
CreatBinTree(&(*BT)->Left);
CreatBinTree(&(*BT)->Right);
}
}
int Count( BinTree BT)//总结点数
{
if(BT==NULL) return 0;
else
return Count(BT->Left)+Count(BT->Right)+1;
}
int YeZiCount(BinTree BT)//叶子结点数
{
if(BT==NULL)
return 0;
if(BT->Left==NULL&&BT->Right==NULL)
return 1;
return YeZiCount(BT->Left)+YeZiCount(BT->Right);
}
void main()
{
printf("请按照先序输入二叉树:\n");
BinTree BT;
CreateBinTree(&BT);
printf("二叉树构造完成!\n");
printf("这棵二叉树的总结点数为:%d\n",Count(BT));
printf("这棵二叉树的叶子结点数为:%d",YeZiCount(BT));
}