My simple c++ solution

  • 0
    class Solution {
    bool validTree(int n, vector<pair<int, int>>& edges) {
        vector<int> nums[n];
        vector<bool> visited(n, false);
        for( auto e: edges){
        if(isCycle(0, -1, visited, nums)) return false;
        for(auto x: visited) {
            if(!x)  return false;    
        return true;    
    bool isCycle(int i,int pre, vector<bool>& visited, vector<int>nums[]){
        visited[i] = true;        
        for(int x : nums[i]){
            if(x != pre)if(visited[x] || isCycle(x, i, visited, nums)) return true;    
        return false;    

Log in to reply

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