LeetCode 261. Graph Valid Tree

原题链接在这里:https://leetcode.com/problems/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.

For 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.

题解:

Union-Find, 与Number of Islands II相似.

Check is edges count is equal to n-1(There is only one cluster after merging).

然后判断有没有环,若是find(edge[0],edge[1])返回true 说明edge[0], edge[1]两个点之前就连在一起了.

Time Complexity: O(n*logn). Space: O(n).

AC Java:

复制代码
 1 public class Solution {
 2     public boolean validTree(int n, int[][] edges) {
 3         if(edges == null || edges.length != n-1){
 4             return false;
 5         }
 6         
 7         UnionFind tree = new UnionFind(n);
 8         for(int [] edge : edges){
 9             if(!tree.find(edge[0], edge[1])){
10                 tree.union(edge[0], edge[1]);
11             }else{
12                 return false;
13             }
14         }
15         return true;
16     }
17 }
18 
19 class UnionFind{
20     int count, n;
21     int [] size;
22     int [] parent;
23     
24     public UnionFind(int n){
25         this.n = n;
26         this.count = n;
27         size = new int[n];
28         parent = new int[n];
29         for(int i = 0; i<n; i++){
30             parent[i] = i;
31             size[i] = 1;
32         }
33     }
34     
35     public boolean find(int i, int j){
36         return root(i) == root(j);
37     }
38     
39     private int root(int i){
40         while(i != parent[i]){
41             parent[i] = parent[parent[i]];
42             i = parent[i];
43         }
44         return i;
45     }
46     
47     public void union(int p, int q){
48         int i = root(p);
49         int j = root(q);
50         if(size[i] > size[j]){
51             parent[j] = i;
52             size[i] += size[j];
53         }else{
54             parent[i] = j;
55             size[j] += size[i];
56         }
57         this.count--;
58     }
59     
60     public int size(){
61         return this.count;
62     }
63 }
复制代码

 

posted @   Dylan_Java_NYC  阅读(724)  评论(0编辑  收藏  举报
编辑推荐:
· 后端思维之高并发处理方案
· 理解Rust引用及其生命周期标识(下)
· 从二进制到误差:逐行拆解C语言浮点运算中的4008175468544之谜
· .NET制作智能桌面机器人:结合BotSharp智能体框架开发语音交互
· 软件产品开发中常见的10个问题及处理方法
阅读排行:
· 2025成都.NET开发者Connect圆满结束
· 后端思维之高并发处理方案
· 千万级大表的优化技巧
· 在 VS Code 中,一键安装 MCP Server!
· 10年+ .NET Coder 心语 ── 继承的思维:从思维模式到架构设计的深度解析
点击右上角即可分享
微信分享提示