1004. Counting Leaves (30)
来源:互联网 发布:知乎 查过敏源 编辑:程序博客网 时间:2024/06/06 17:14
1. 原题链接
1004. Counting Leaves (30)
2. 理解题目
给出一棵树的信息(不是二叉树),格式:父结点id 子结点个数 子结点id ;求出每一层的叶子结点的个数;
(根结点的id=01,层数为1)
3. 解题思路
[思路]
可以采用结构体来存储孩子结点的id:由于孩子结点个数不确定,所以可以采用vector的C++容器进行保存,比较方便;
用一个数组leafnode[]来保存每一层的叶子结点个数;要求出每一层的叶子结点个数,则肯定要遍历;这里采用DFS来遍历,用递归的写法;
然后判断该结点的子孩子是否有,如果没有就在对应层leafnode[]数组中加一;最后输出leafnode[]的内容即可;
备注:题目中的seniority level是什么意思??如果可以理解,欢迎邮箱交流~~
4. 关键点
[提炼模板]: DFS中,可以用根节点id进行递归,同时增加参数layer可以用于标记对应层;
5. AC代码
#include<cstdio>#include<vector>using namespace std;const int maxn=110;struct Node{ vector<int> ch;//vector<int> 数组ch; }node[maxn];int leafnode[maxn]={0};//每层的叶结点个数 int lay_max=0;//最大层数void dfs(int root,int layer){ lay_max=lay_max>layer? lay_max:layer; //遍历过程中保存最大层数 if(node[root].ch.size()==0){ leafnode[layer]++; //对应层的叶子节点数加1 return; }else{ for(int i=0;i<node[root].ch.size();i++){ dfs(node[root].ch[i],layer+1); } }}int main(){ int n,m;scanf("%d%d",&n,&m); int id,num,tmp; //记录树信息 for(int i=0;i<m;i++){ scanf("%d%d",&id,&num); for(int j=0;j<num;j++){ scanf("%d",&tmp); node[id].ch.push_back(tmp); } } dfs(1,1); //递归开始:根节点Id和对应的层号1; for(int i=1;i<=lay_max;i++){ if(i==1) printf("%d",leafnode[i]); else printf(" %d",leafnode[i]); }}
阅读全文
0 0
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- 1004. Counting Leaves (30)
- NuGet无法下载问题
- javaScript翻页功能
- phpmailer 发送图片
- JS——数组(引用传递)
- spark基础之spark streaming的checkpoint机制
- 1004. Counting Leaves (30)
- Maven学习
- 分布式事务之——tcc-transaction分布式TCC型事务框架搭建与实战案例(基于Dubbo/Dubbox)
- LeetCode 114. Flatten Binary Tree to Linked List 拉平二叉树 Python Solution
- 根据字符长度,控制在TextView显示多少行
- JavaScript arguments对象
- Linux命令操作
- 0的timestamp类型时不能正确的处理zeroDateTimeBehavior
- 码流 / 码率 / 比特率 / 帧速率 / 分辨率 / 高清的区别