My C++ solution - easy to understand!!!


  • 0
    E
    class Solution {
    public:
        bool validTree(int n, vector<pair<int, int>>& edges) {
            vector<int> node(n, 0);
            for(int i = 0 ; i < n ; ++i) {
                node[i] = i;
            }
            for(auto edge : edges) {
                int val1 = edge.first;
                int val2 = edge.second;
                while(node[val1] != val1) {
                    val1 = node[val1];
                }
                while(node[val2] != val2) {
                    val2 = node[val2];
                }
                if(val1 == val2) {
                    return false;
                }
                node[val2] = val1;
            }
            return n == edges.size() + 1;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.