7-1(提示:森林可采用先序递归创建+分别用递归与分治求叶子数、基于树的遍历求叶子数) 树或森林求叶子

题目描述:小高学完树的知识点后觉得很简单,觉得做什么都很简单,直到遇见本题:要求自己摸索本题森林的输入方式,并用两种方式求出森林中树的叶子节点。

输入格式:

根据输入样例自行判断。

输出格式:

输出森林有几个叶子节点,且格式为‘该森林叶子结点数为n!’

输入样例:

在这里给出一组输入。例如:

1
1
1
0
0
1
0
0
1
1
1
0
0
1
0
0
0

输出样例:

在这里给出相应的输出。例如:

该森林叶子结点数为4!

该森林叶子结点数为4!
//头文件包含
#include<iostream>
#include<malloc.h>
#include<stdio.h>
using namespace std;
 
//函数状态码定义
#define TRUE       1
#define FALSE      0
#define OK         1
#define ERROR      0
#define OVERFLOW   -1
#define INFEASIBLE -2
#define NULL  0
typedef int Status;
int s[20];
int cnt=0;
//二叉链表存储结构定义
typedef int TElemType;
typedef struct CSNode
{
    TElemType data;
    struct CSNode *firstchild;
    struct CSNode *nextsibling;
}CSTNode,*CSTree;
 
Status CreateCSTree(CSTree &CST)
{
    TElemType e;
    e=s[cnt];
    cnt++;
    if(e==0)
        CST=NULL;
    else
    {
        CST=(CSTNode*)malloc(sizeof(CSTNode));
        if(!CST)
            exit(OVERFLOW);
        CST->data=e;
        CreateCSTree(CST->firstchild);
        CreateCSTree(CST->nextsibling);
    }
    return OK;
}
int LealvesCounter(CSTree &T){
    if(!T){return 0;}
   else if(!T->firstchild) { return 1; }
    else{
        return LealvesCounter(T->firstchild)+LealvesCounter(T->nextsibling);
    }
}
 
 
int main()
{
    CSTree CST;
 
    for(int j=0;j<17;++j)
    {  scanf("%d",&s[j]);
 
 
    }  CreateCSTree(CST);
    printf("该森林叶子结点数为%d!\n\n",LealvesCounter(CST)) ;
    printf("该森林叶子结点数为%d!\n",LealvesCounter(CST)) ;
    
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值