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

Hint:

  1. Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree?
  2. According to the definition of tree on Wikipedia: “a tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree.”

Note: 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.


思路:判断一个图是不是一棵树①首先应该有n-1条边 ②边没有形成环

判断是否有环的步骤如下:

1.保存每一个结点的父结点,初始为每个结点的父结点指向自己.

2.这样每次遍历一条边的时候我们追踪这两个结点,直到其最终父结点.

3.如果其最终父结点相同,则说明他们构成了环,返回false

4.否则就将第一个结点的最终父结点作为第二个结点最终父结点的父结点.也就是说到了最后,所有结点最终只有一个父结点.

代码如下:

class Solution {
public:
    bool validTree(int n, vector<pair<int, int>>& edges) {
        if(edges.size() != n-1) return false;
        vector<int> node(n, 0);
        for(int i =0; i< n; i++) node[i] = i;
        for(auto val: edges)
        {
            int fir = val.first, sec = val.second;
            while(node[fir] != fir) 
                fir = node[fir];
            while(node[sec] != sec) 
                sec = node[sec];
            if(node[fir] == node[sec]) return false;
            node[sec] = fir;
        }
        return true;
    }
};
参考:https://leetcode.com/discuss/66984/simple-and-clean-c-solution-with-detailed-explanation

你可能感兴趣的:(LeetCode,Graph,Facebook)