这道题卡在了如果没有连接起来是断的时候怎么处理?卡在这个测试用例了[[0,1],[2,3]]
解决
在确保图是否为树的算法中,我们需要考虑以下几点:
- 树的定义:一个连通的无向无环图。
- 节点数和边数:对于
n个节点的树,应该有n-1条边。 - 连通性:从任意一个节点出发应该能够访问到所有其他节点。
- 无环性:在遍历过程中,确保不访问已经访问过的节点,除非是从父节点回溯。
根据以上思想,得出:
class Solution {
int N = 2010, M = N * 4, idx = 0;
int[] e = new int[M], ne = new int[M], h = new int[N];
public void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
public boolean validTree(int n, int[][] edges) {
if(edges.length != n - 1) {
return false;
}
Arrays.fill(h, -1);
for(int[] e : edges) {
add(e[0], e[1]);
add(e[1], e[0]);
}
boolean[] st = new boolean[n];
dfs(0, -1, st);
for(int i = 0;i < n;i ++) {
if(!st[i]) return false;
}
return true;
}
public boolean dfs(int now, int parent, boolean[] st) {
st[now] = true;
for(int i = h[now];i != -1;i = ne[i]) {
int next = e[i];
if(next == parent) continue;
if(st[next] || !dfs(next, now, st)) return false;
}
return true;
}
}