Skip to content

Instantly share code, notes, and snippets.

@chiihuang
Created May 7, 2017 00:01
Show Gist options
  • Save chiihuang/e654fe97ac518bd0dcd8f098e6bdda62 to your computer and use it in GitHub Desktop.
Save chiihuang/e654fe97ac518bd0dcd8f098e6bdda62 to your computer and use it in GitHub Desktop.
leetcode 261 solution
class Solution {
public:
bool validTree(int n, vector<pair<int, int>>& edges) {
vector<int> group(n + 1, -1);
for(auto e : edges){
int x = find(group, e.first);
int y = find(group, e.second);
if (x == y) return false;
group[x] = y;
}
return edges.size() == n - 1;
}
int find(vector<int>& group, int i){
if (group[i] == -1) return i;
return find(group, group[i]);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment