Problem
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.
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.
Note
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.
Solution
public class Solution {
int[] parents;
public boolean validTree(int n, int[][] edges) {
if (n-1 != edges.length) {
return false;
}
parents = new int[n];
//initialize n nodes as each own parent
for (int i = 0; i < n; i++) {
parents[i] = i;
}
for (int i = 0; i < n-1; i++) {
if (find(edges[i][0]) == find(edges[i][1])) {
return false; //if two nodes on edge[i] have the same parent, this edge makes a circle causing it invalid
}
else union(edges[i][0], edges[i][1]); //else union the two nodes on edge[i]
}
return true;
}
public int find(int node) {
//find the very first parent node, which is when the parent is the node itself
if (parents[node] == node) {
return node;
}
//find parent recursively
return find(parents[node]);
}
public void union(int a, int b) {
int finda = parents[a], findb = parent[b];
//when node a and node b have different ancient parents, union them with the same parent
if (finda != findb) {
parents[finda] = findb;
}
}
}
Update 2018-10
class Solution {
public boolean validTree(int n, int[][] edges) {
if (edges.length != n-1) return false;
int[] nums = new int[n];
Arrays.fill(nums, -1);
for (int i = 0; i < edges.length; i++) {
int x = find(nums, edges[i][0]);
int y = find(nums, edges[i][1]);
if (x == y) return false;
nums[x] = y;
}
return true;
}
private int find(int[] nums, int k) {
if (nums[k] == -1) return k;
else return find(nums, nums[k]);
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。