My issue
I use an adjacency list to store the tree structure. Using depth first search I search for the node v in question. Upon match I check whether this was the root node or not. Counting all direct children plus 1 (has a parent node) or 0 (has no parent node) gives me the final result (number of neighbors). This works fine against the given example but fails apparently in my submission. Any help is highly appreciated. The special case of no node v found results in 0. The call stack should not get exhausted if the used compiler applies tail call elimination and no such error has been given.
My code
#include <bits/stdc++.h>
using namespace std;
static vector<int> tree[100005];
static size_t dfs(const int u, const int v) {
if (u == v) {
// node in question
if (u == 1) {
// root node
return tree[u].size();
}
// inner node
return 1 + tree[u].size();
} else for (const int i : tree[u]) {
// some node
return dfs(i, v);
}
// node v not found
return 0;
}
int main() {
int n, v;
cin >> n >> v;
for (int i = 1; i < n; i++) {
int u, v;
cin >> u >> v;
tree[u].push_back(v);
}
cout << dfs(1, v) << endl;
}
Learning course: Trees and Binary trees
Problem Link: Neighbours of node Practice Problem in Trees and Binary trees - CodeChef