[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> &edges) {
        // write your code here
        if (n <= 0)
            return false;
        vector 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!

你可能感兴趣的:(LeetCode)