Skip to content

Commit 2c2fef9

Browse files
authored
Update 310.Minimum-Height-Trees.cpp
1 parent ed9be62 commit 2c2fef9

File tree

1 file changed

+22
-20
lines changed

1 file changed

+22
-20
lines changed

BFS/310.Minimum-Height-Trees/310.Minimum-Height-Trees.cpp

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,24 +4,26 @@ class Solution {
44
{
55
if (n==1) return {0};
66
if (n==2) return {0,1};
7-
8-
vector<int>inDegree(n);
7+
98
vector<vector<int>>next(n);
10-
for (auto edge:edges)
9+
vector<int>degree(n);
10+
11+
for (auto edge: edges)
1112
{
12-
inDegree[edge[0]]++;
13-
inDegree[edge[1]]++;
14-
next[edge[0]].push_back(edge[1]);
15-
next[edge[1]].push_back(edge[0]);
13+
int a = edge[0], b = edge[1];
14+
degree[a]++;
15+
degree[b]++;
16+
next[a].push_back(b);
17+
next[b].push_back(a);
1618
}
1719

1820
queue<int>q;
1921
vector<int>visited(n);
2022
for (int i=0; i<n; i++)
2123
{
22-
if (inDegree[i]==1)
23-
q.push(i);
24-
}
24+
if (degree[i]==1)
25+
q.push(i);
26+
}
2527

2628
int count = 0;
2729
while (!q.empty())
@@ -31,26 +33,26 @@ class Solution {
3133
{
3234
int cur = q.front();
3335
q.pop();
36+
count++;
3437
visited[cur] = 1;
35-
count++;
3638
for (int nxt: next[cur])
3739
{
38-
inDegree[nxt]--;
39-
if (inDegree[nxt]==1)
40+
degree[nxt]--;
41+
if (degree[nxt]==1)
4042
q.push(nxt);
41-
}
42-
}
43+
}
44+
}
4345
if (count==n-1 || count==n-2)
44-
break;
46+
break;
4547
}
4648

4749
vector<int>rets;
48-
for (int i=0; i<n; i++)
50+
while (!q.empty())
4951
{
50-
if (visited[i]==0)
51-
rets.push_back(i);
52+
rets.push_back(q.front());
53+
q.pop();
5254
}
53-
55+
5456
return rets;
5557

5658
}

0 commit comments

Comments
 (0)