[Hacker Rank] Even Tree

Even Tree

  • Time : O(v)
  • Space : O(v + e)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
vector<int> adj[101];
bool dfs(int u, int par, int& res) {
bool even = false;
for(auto& v : adj[u]) {
if(v == par) continue;
if(dfs(v, u, res)) res++;
else even = !even;
}
return even;
}

int evenForest(int v, int e, vector<int> t, vector<int> f) {
for(int i = 1; i <= v; i++) adj[i].clear();
for(int i = 0; i < e; i++) {
adj[t[i]].push_back(f[i]);
adj[f[i]].push_back(t[i]);
}
int res = 0;
dfs(1, -1, res);
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/08/PS/HackerRank/even-tree/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.