Fork me on GitHub

Graph Valid Tree

Description

https://leetcode.com/problems/graph-valid-tree/

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

Example 1:

1
2
Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
Output: true

Example 2:

1
2
Input: n = 5, and edges = [[0,1], [1,2], [2,3], [1,3], [1,4]]
Output: false

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

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public:
bool validTree(int n, vector<pair<int, int>>& edges) {
if (n == 0 || n == 1) return true;
vector<int> status(n, 0);
unordered_map<int, vector<int>> edgeMap;

for (auto& item : edges) {
edgeMap[item.first].push_back(item.second);
edgeMap[item.second].push_back(item.first);
}

if (edgeMap.count(0) == 0) return false;
bool hasLoop = false;
traverse(edgeMap, status, 0, hasLoop, -1);
if (hasLoop == true) return false;

//Check is directed graph
for (int i = 1; i < n; ++i) {
if (status[i] != 1) return false;
}

return true;
}

void traverse(unordered_map<int, vector<int>>& edgeMap,
vector<int>& status, int index, bool& hasLoop, int pre) {
if (hasLoop == true || status[index] == 1) return;
if (status[index] == - 1) {
hasLoop = true;
return;
}

auto& lis = edgeMap[index];
status[index] = -1; //Mark as pending
for (auto& item : lis) {
if (item == pre) continue;
traverse(edgeMap, status, item, hasLoop, index);
}

status[index] = 1; //Mark as visit
return;
}
};