310. Minimum Height Trees LeetCode
2016-03-16 14:50
429 查看
题意:给出一张图,选一个节点作为根使得这棵树最矮,求所有这样的节点。
题解:有点像拓扑排序的做法,就是从度为1的点一层一层往里面扩展,最后剩下的点就是树根。
题解:有点像拓扑排序的做法,就是从度为1的点一层一层往里面扩展,最后剩下的点就是树根。
class Solution { public: vector<int> findMinHeightTrees(int n, vector<pair<int, int>>& edges) { if(n == 1) return vector<int>{0}; vector<vector<int>> edge; vector<int> vis,d,ans; for(int i = 0; i <= n; i++) { edge.push_back(vector<int>{}); vis.push_back(0); d.push_back(0); } for(int i = 0; i < edges.size(); i++) { int u = edges[i].first; int v = edges[i].second; edge[u].push_back(v); edge[v].push_back(u); d[u]++; d[v]++; } queue<int> q; while(!q.empty()) q.pop(); for(int i = 0; i < n; i++) if(d[i] == 1) q.push(i),vis[i] = 1; while(!q.empty()) { int n = q.size(); ans.clear(); for(int k = 1; k <= n; k++) { int now = q.front(); q.pop(); ans.push_back(now); for(int i = 0; i < edge[now].size(); i++) { int v = edge[now][i]; if(!vis[v]) { d[v]--; if(d[v] == 1) { q.push(v); vis[v] = 1; } } } } } return ans; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解