统计二叉树中具有度为1的结点数目

题目:

根据带虚结点的先序序列建立二叉树,再统计输出二叉树中具有度为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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值