Graph Valid Tree
犯错:这个题一开始不用check edge的合法性,因为n=1的时候,没有edge是true的,n=2时没有edge是不合法的,所以直接让n和edge的关系去判断就好了
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 1:
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true
Example 2:
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: 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
.
class Solution { public boolean validTree(int n, int[][] edges) { if(n <= 0){ return false; }
valid tree: edge 数比node数 小1, 无环, 用bfs判断,结束以后,bfs遍历的点,一定和node数一样才对
if(edges.length != n-1)
return false;
Map<Integer,Set<Integer>> map = buildTree(n,edges);
Queue<Integer> queue = new LinkedList<>();
Set<Integer> hash = new HashSet<>();
queue.offer(0);
hash.add(0);
while(!queue.isEmpty()){
int node = queue.poll();
for(int nb : map.get(node)){
if(hash.contains(nb)){
continue;
}
hash.add(nb);
queue.offer(nb);
}
}
return hash.size() == n;
}
public Map<Integer,Set<Integer>> buildTree(int n, int[][] edges){
Map<Integer,Set<Integer>> map = new HashMap<>();
for(int i = 0; i < n;i++){
map.put(i, new HashSet<>());
}
for(int i = 0; i < edges.length;i++){
int u = edges[i][0];
int v = edges[i][1];
map.get(u).add(v);
map.get(v).add(u);
}
return map;
}
}
Last updated