-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy path310-gusrb3164.cpp
53 lines (52 loc) · 1.26 KB
/
310-gusrb3164.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
class Solution
{
public:
vector<int> findMinHeightTrees(int n, vector<vector<int>> &edges)
{
if (n <= 1)
return {0};
vector<vector<int>> graph(n);
for (auto &edge : edges)
{
graph[edge[0]].push_back(edge[1]);
graph[edge[1]].push_back(edge[0]);
}
vector<int> leaves;
for (int i = 0; i < n; i++)
{
if (graph[i].size() == 1)
{
leaves.push_back(i);
}
}
while (n > 2)
{
n -= leaves.size();
vector<int> newLeaves;
//i = 해당 n
for (auto leaf : leaves)
{
int next = graph[leaf][0];
rmNum(graph[next], leaf);
if (graph[next].size() == 1)
{
newLeaves.push_back(next);
}
}
leaves = newLeaves;
}
return leaves;
}
//벡터내의 특정 값 지우는 함수
void rmNum(vector<int> &nums, int num)
{
for (int i = 0; i < nums.size(); i++)
{
if (nums[i] == num)
{
nums.erase(nums.begin() + i);
return;
}
}
}
};