1004. Counting Leaves (30)

1.可为多叉树,采用vector<string>保存子树名称

2.采用map记录树节点

3.采用广度遍历,输出每层的叶子节点数量


节点代码如下:

struct node{
	vector<string> child;
	int head;
	string ID;
	node() :head(-1), child(0), ID(""){};
};

源代码:

//#include<string>
//#include <iomanip>
#include<vector>
#include <algorithm>
//#include<stack>
#include<set>
#include<queue>
#include<map>
//#include<unordered_set>
//#include<unordered_map>
//#include <sstream>
//#include "func.h"
//#include <list>
#include<stdio.h>
#include<iostream>
#include<string>
#include<memory.h>
using namespace std;
#define maxDist 999999
struct node{
	vector<string> child;
	int head;
	string ID;
	node() :head(-1), child(0), ID(""){};
};

int main(void) {

	int n, m;
	cin >> n >> m;

	map<string, node> tree;
	for (int i = 0; i < m; i++)
	{//循环输入父子关系
		string ID;
		cin >> ID;
		tree[ID].ID = ID;
		int k;
		cin >> k;
		for (int i = 0; i < k; i++)
		{
			string tmp;
			cin >> tmp;
			tree[ID].child.push_back(tmp);
			tree[tmp].ID = tmp;
			tree[tmp].head++;
		}
	}
	//需要建立一个前头节点,便于循环计算
	tree["superhead"].ID = "";
	tree["superhead"].child = vector<string>(0);
	tree["superhead"].head = 100;
	string headID = "";
	tree["superhead"].child.push_back("01");
	headID = "superhead";
	queue<string> q;
	q.push(headID);
	vector<int> ans(0);
	int count1 = 1;
	int count2 = 0;
	int leaf = 0;
	while (!q.empty())
	{
		for (int k = 0; k < count1; k++)
		{//上一层有count1个
			string top = q.front();
			q.pop();
			for (int i = 0; i < tree[top].child.size(); i++)
			{
				string tmp = tree[top].child[i];
				if (tree[tmp].child.size() == 0)
					leaf++;//如果没有子节点,那么就是叶子节点
				else
				{
					q.push(tmp);//有子节点,压进队列,继续遍历
					count2++;
				}
			}
		}
		ans.push_back(leaf);
		leaf = 0;
		count1 = count2;
		count2 = 0;
	}
	for (int i = 0; i < ans.size(); i++)
	{
		cout << ans[i];
		if (i != ans.size() - 1)
			cout << " ";
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值