Sharing my 256ms C++ solution


  • 1
    T
    class Solution {
    private:
        void validTreeHelper(int n, vector<vector<int>>& myMap, vector<bool>& visited, int& nPointsLeft)
        {
            if(visited[n]==true)
                return;
            else
            {
                visited[n]=true;
                nPointsLeft--;
            }
            
            vector<int> v = myMap[n];
            for(int i=0; i<v.size(); i++)
                validTreeHelper(v[i], myMap, visited, nPointsLeft);
        }
        
    public:
        bool validTree(int n, vector<pair<int, int>>& edges) {
            vector<vector<int>> myMap(n, vector<int>(0));
            int first, second, N = edges.size(), i;
            for(i=0; i<N; i++)
            {
                first = edges[i].first;
                second = edges[i].second;
                myMap[first].push_back(second);
                myMap[second].push_back(first);
            }
            
            vector<bool> visited(n, false);
            int nPointsLeft = N+1;
            validTreeHelper(0, myMap, visited, nPointsLeft);
            if(nPointsLeft>0)
                return false;
                
            for(i=0; i<n; i++)
                if(visited[i]==false)
                    return false;
                    
            return true;
        }
    };

  • 0
    H

    A nice DFS solution


Log in to reply
 

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