返回题解分享
讨论 / 题解分享/ 帖子详情

树的广度优先遍历 - 题解

// https://dashoj.com/p/131
#include <bits/stdc++.h>

using namespace std;
int n;
map<int, vector<int>> tree;

void bfs() {
	queue<int> q;
	q.push(1);
	while (!q.empty()) {
		int x = q.front();
		q.pop();
		cout << x << ' ';
		for (int i: tree[x]) q.push(i);
	}
}

int main() {
	cin >> n;
	for (int i = 1; i < n; i++) {
		int x, y;
		cin >> x >> y;
		tree[x].push_back(y);
	}
	bfs();
	return 0;
}
0 回复 0 转发 0 喜欢 2 阅读
回复 (0)
默认 最新
暂无回复,快来抢沙发!