题目:
根据带虚结点的先序序列建立二叉树,再统计输出二叉树中具有度为1的结点数目。
输入格式:
测试数据有多组,处理到文件尾。每组测试数据在一行中输入一个字符串(不含空格且长度不超过80),表示二叉树的先序遍历序列,其中字符*
表示虚结点(对应的子树为空)。
输出格式:
对于每组测试,对所建立的二叉树,输出该二叉树中具有度为1的结点数目。输出格式为:“num: d”,其中d为二叉树中具有度为1的结点数目。
输入样例:
HDA**C*B**GF*E***
A*B*C*D*E*F**
输出样例:
num: 3
num: 5
答案:
#include<stdio.h>
#include<stdlib.h>
#define ERROR 0
#define OVERFLOW -1
typedef struct BiTNode
{
char data;
struct BiTNode *lchild;
struct BiTNode *rchild;
} BiTNode,*BiTree;
//创建新节点的函数
BiTNode* CreateNode(char e){
BiTNode* node=(BiTNode*)malloc(sizeof(BiTNode));
if(!node) exit(OVERFLOW);
node->data=e;
node->lchild=NULL;
node->rchild=NULL;
return node;
}
//根据前序序列构建二叉树
BiTree CreateBiTree(char* str,int* index){
if(str[*index]=='\0'||str[*index]=='*'){
(*index)++;
return NULL;
}
BiTNode* node=CreateNode(str[*index]);
(*index)++;
node->lchild=CreateBiTree(str,index);
node->rchild=CreateBiTree(str,index);
return node;
}
//求度
int BiTreeNodeDegreeOneCount(BiTree &T)
{
if(T==NULL)return 0;
int count=0;
if( (T->lchild==NULL&&T->rchild!=NULL)||(T->rchild==NULL&&T->lchild!=NULL) )
{
count=1;
}
return count+BiTreeNodeDegreeOneCount(T->lchild) + BiTreeNodeDegreeOneCount(T->rchild);
}
int main() {
char str[100];
while(fgets(str,sizeof(str),stdin)){
int index=0;
BiTree tree = CreateBiTree(str, &index); // 创建二叉树
int count = BiTreeNodeDegreeOneCount(tree); // 计算度为1的节点数量
printf("num: %d\n", count); // 输出结果
}
return 0;
}