[Leetcode] Graph Valid Tree

Source: Internet
Author: User

Problem Description:

Given n nodes labeled from 0 n - 1 to and a list of undirected edges (each edge is a pair of nodes), write a funct Ion to check whether these edges make up a valid tree.

For example:

Given n = 5 edges = [[0, 1], [0, 2], [0, 3], [1, 4]] and, return true .

Given n = 5 edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]] and, return false .

Hint:

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

Note:you can assume that no duplicate edges would appear in edges . Since all edges was undirected, is the same as and thus would not [0, 1] [1, 0] appear together in edges .

As suggested by the hint, just check for cycle and connectedness in the graph. Both of these can be done via DFS.

The code is as follows.

1 classSolution {2  Public:3     BOOLValidtree (intN, vector<pair<int,int>>&edges) {4vector<vector<int>>Neighbors (n);5          for(Auto e:edges) {6 Neighbors[e.first].push_back (e.second);7 Neighbors[e.second].push_back (e.first);8         }9vector<BOOL> Onpath (N,false), visited (N,false);Ten         if(Hascycle (Neighbors,0, -1, Onpath, visited)) One             return false; A          for(BOOLv:visited) -             if(!V)return false;  -         return true; the     } - Private: -     BOOLHascycle (vector<vector<int>>& Neighbors,intKidintParent, vector<BOOL>& Onpath, vector<BOOL>&visited) { -         if(Onpath[kid])return true; +Onpath[kid] = Visited[kid] =true; -          for(Auto Neigh:neighbors[kid]) +             if(neigh! = parent &&hascycle (Neighbors, neigh, Kid, Onpath, visited)) A                 return true; at         returnOnpath[kid] =false; -     } -};

[Leetcode] Graph Valid Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.