[LeetCode 261] 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

Example 1:

Input: n = 5 edges = [[0, 1], [0, 2], [0, 3], [1, 4]]
Output: true.

Example 2:

Input: n = 5 edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]]
Output: 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.

 

分析

这一题首先要考虑有几种情况会导致不是valid tree.

1. 含有环

2. 所有的Node不在同一个tree中

这道题首先判断是否有n-1条边,当小于n-1条边时,则必然无法组成连通图,如果大于n-1时,由于不存在重复的节点,则必然存在环。然后选取一个节点进行广度优先搜索,使用set存放搜索过的点,如果搜索的点在set中表明有环。直到最终结果要求set的size == n。

还可以使用并查集的方法去做,并查集与树有天然的相同性,一个树所组成的并查集必定有且只有一个集合。而且在遍历边的过程中两个node之间必然不是同一个集合。Code给出并查集的解法。

Code

class Solution {
public:
    /**
     * @param n: An integer
     * @param edges: a list of undirected edges
     * @return: true if it's a valid tree, or false
     */
    bool validTree(int n, vector<vector<int>> &edges) {
        // write your code here
        if (n <= 0)
            return false;
        vector<int> uf(n, 0);
        for (int i = 0; i < n; i ++)
        {
            uf[i] = i;
        }
        
        int len = edges.size();
        for (int i = 0; i < len; i ++)
        {
            int p = edges[i][0];
            int q = edges[i][1];
            while (p != uf[p]) p = uf[p];
            while (q != uf[q]) q = uf[q];
            if (p == q)
                return false;
            uf[q] = p;
        }
        
        int root = 0;
        while (uf[root] != root)
            root = uf[root];
        for (int i = 1; i < n; i ++)
        {
            int node = i;
            while (uf[node] != node)
                node = uf[node];
            
            if (node != root)
                return false;
        }
  
        return true;
    }
    
};

运行效率

our submission beats 32.60% Submissions!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值