Data Structures and Algorithms7-21——Counting Leaves

本博客介绍了一种使用C++实现的树的层序遍历算法,用于统计每层的叶子节点数量。该算法适用于处理多个测试用例,并详细展示了如何通过广度优先搜索(BFS)遍历树结构,同时记录各层叶子节点的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我的Data Structures and Algorithms代码仓:https://github.com/617076674/Data-Structures-and-Algorithms

原题链接:https://pintia.cn/problem-sets/16/problems/683

题目描述:

知识点:树的静态表示法、树的层序遍历

思路:层序遍历树,记录每一层的叶子节点数量

本题和PAT-ADVANCED1004——Counting Leaves的解法一模一样,只不过PAT-ADVANCED1004——Counting Leaves中一个输入文件只包含一个测试用例,而本题中一个输入文件包含多个测试用例。

每个测试用例的时间复杂度和空间复杂度都是O(N)。

C++代码:

#include<iostream>
#include<vector>
#include<queue>

using namespace std;

struct node {
	vector<int> children;
};

int N, M, ID, K, child;

void bfs(node* Node, vector<int> &levelLeaves);

int main() {
	while(true) {
		scanf("%d %d", &N, &M);
		if(N == 0) {
			break;
		}
		node Node[N + 1];
		for(int i = 0; i < M; i++) {
			scanf("%d %d", &ID, &K);
			for(int j = 0; j < K; j++) {
				scanf("%d", &child);
				Node[ID].children.push_back(child);
			}
		}
		vector<int> levelLeaves;
		bfs(Node, levelLeaves);
		for(int i = 0; i < levelLeaves.size(); i++){
			printf("%d", levelLeaves[i]);
			if(i != levelLeaves.size() - 1){
				printf(" ");
			}else{
				printf("\n");
			}
		}
	}
	return 0;
}

void bfs(node* Node, vector<int> &levelLeaves) {
	queue<int> q;
	q.push(1);
	while(!q.empty()) {
		int qSize = q.size();
		int count = 0;
		for(int i = 0; i < qSize; i++) {
			int u = q.front();
			q.pop();
			if(Node[u].children.size() == 0){
				count++;
			}
			for(int j = 0; j < Node[u].children.size(); j++){
				q.push(Node[u].children[j]);
			}
		}
		levelLeaves.push_back(count);
	}
}

C++解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值