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!
博客围绕判断给定节点和边能否构成有效树展开。指出非有效树的情况,如含环、节点不在同一树中。介绍两种判断方法,一是判断边数,再用广度优先搜索查环;二是用并查集,一个有效树的并查集只有一个集合,且边的两节点不在同一集合,还给出并查集解法代码。

727

被折叠的 条评论
为什么被折叠?



