Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
Notice:
You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
Example:
Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
classSolution { public: /** * @param n an integer * @param edges a list of undirected edges * @return true if it's a valid tree, or false */ boolvalidTree(int n, vector<vector<int>>& edges){ // Write your code here if (n - 1 != edges.size()) returnfalse; int rootCount = 0; vector<int> t(n, 0); vector<int> pre(n, 0); for (int i = 1; i < n; i++) pre[i] = i; for (int i = 0; i < edges.size(); i++) { //if node connect to itself or not. if (edges[i][0] == edges[i][1]) returnfalse; unionOp(pre, edges[i][0], edges[i][1]); } for(int i = 0; i < n; i++) { t[findOp(pre, i)] = 1; } for(int i = 0; i < n; i++) { if (t[i]) rootCount++; } if (rootCount > 1) returnfalse; returntrue; } intfindOp(vector<int> &pre, int x){ int r = x; while(r != pre[r]) r = pre[r]; int i = x, j; while(pre[i] != r) { j = pre[i]; pre[i] = r; i = j; } return r; } voidunionOp(vector<int> &pre, int x, int y){ int fx = findOp(pre, x), fy = findOp(pre, y); if(fx != fy) { pre[fy] = fx; } } };