- Graph Valid Tree
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.
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.
一棵树必须具备如下特性:
(1)是一个全连通图(所有节点相通)
(2)无回路
其中(2)等价于:(3)图的边数=节点数-1
因此我们可以利用特性(1)(2)或者(1)(3)来判断。
图的构建方式:HashMap<Integer,HashSet> graph = new HashMap<>(); 用map存储节点和相邻节点
public boolean validTree(int n, int[][] edges) {
// write your code here
if(n == 0 || edges.length != n - 1) return false;
HashMap<Integer,HashSet<Integer>> graph = initGraph(n,edges);
Queue<Integer> queue = new LinkedList<>();
HashSet<Integer> hash = new HashSet<>();
queue.offer(0);
hash.add(0);
while(!queue.isEmpty()){
int node = queue.poll();
for(int neighbor : graph.get(node)){
if(hash.contains(neighbor)){
continue;
}
queue.offer(neighbor);
hash.add(neighbor);
}
}
return hash.size() == n;
}
private HashMap initGraph(int n, int[][] edges){
HashMap<Integer,HashSet<Integer>> graph = new HashMap<>();
for(int i = 0; i < n; i++){
graph.put(i, new HashSet<Integer>());
}
for(int i = 0; i < edges.length; i++){
int u = edges[i][0];
int v = edges[i][1];
graph.get(u).add(v);
graph.get(v).add(u);
}
return graph;
}