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:
-
- Given
n = 5
edges = [[0, 1], [1, 2], [3, 4]]
and, what should your return? Is this case a valid tree?
- 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