[LintCode][Tree] Graph Valid Tree

Problem

More Discussions

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.

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.

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.

Solution

问题的本质就是判断图中有没有环,并且所有的点都联通。
那么我们可以用DFS来遍历所有的点,同时做一些判断

  1. 给每个点设颜色:0:未遍历过 1:遍历过一次 2:遍历过2次。那么很容易的可以知道如果有一个点遍历过2次,那肯定存在环。如果DFS之后有一个点从未遍历过,那这个点就在另一个图中,所以也无法构成数。
  2. 另外在判断当前点的下面的遍历节点时,我们要出去它的父亲节点,这样可以避免一条边被重复遍历。
class Solution {
private:
    vector<vector<int>> nodes;
    vector<int> nodeColor;
    
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) {
        if (n == 0) {
            return true;
        }
        nodes.resize(n);
        nodeColor.resize(n);
        for(int i = 0; i < edges.size(); i++) {
            int node1 = edges[i][0];
            int node2 = edges[i][1];
            nodes[node1].push_back(node2);
            nodes[node2].push_back(node1);
        }
        for(int i = 0; i < nodeColor.size(); i++) {
            nodeColor[i] = 0;
        }
        bool result = check(0, -1);
        if (!result) {
            return false;
        }
        
        for(int i = 0; i < n; i++) {
            if (nodeColor[i] == 0) {
                return false;
            }
        }
        
        return true;
    }
    
    bool check(int index, int parentIndex) {
        nodeColor[index]++;
        if (nodeColor[index] == 2) {
            return false;
        }
        
        for(int i = 0; i < nodes[index].size(); i++) {
            if (nodes[index][i] != parentIndex) {
                bool result = check(nodes[index][i], index);
                if (!result) {
                    return false;
                }
            }
        }
        
        return true;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,352评论 0 33
  • 3.1 Graphs Represent a graph by Adjacency matrix -- spars...
    暗黑破坏球嘿哈阅读 7,967评论 0 0
  • 尊敬的领导,老师,同学们: 大家中午好。我是09级新生王会。此刻我作为上届学生会成员代表,能够在此发言我倍感荣幸。...
    栋栋八阅读 3,294评论 0 3
  • “梧桐更兼细雨,到黄昏,点点滴滴。这次第,怎一个愁字了得?”翻开诗集,墨色的仿宋体,清隽的印着易安的黄昏,于...
    微微一笑很虔诚阅读 2,790评论 0 0
  • 我想来这个没有人认识我的地方发画~尽量每天打,等一段时间之后来看自己的进步~记录一下我的成长 我的画实在是问题很大...
    韩小小小旭阅读 1,079评论 0 0