I was doing leetcode 834
. Sum of Distances in Tree, and I figure a way to solve it with two dfs
.
But, the first solution received tle when experienced a test set of 10000 nodes. After seeing the answer, I did some simple changes and the answer was accepted.
I don't know why these two functions perform so differently since they are all O(n)
.
The dfs function is aimed to calculate how many nodes are there under node 'current' and store them in an array 'child'. 'tree' is a 2D vector that contains the edges of the tree in list structure.
old function which received tle:
int dfs(vector <vector <int>> tree, int previous, int current)
{
int s = tree[current].size();
int r = 0;
for (int i = 0; i < s; ++i){
if (tree[current][i] == previous) continue;
r += dfs(tree, current, tree[current][i]);
}
child[current] = r;
d_root += r;
return r + 1;
}
new function that is accepted:
void dfs(int previous, int current)
{
int s = tree[current].size();
int r = 0;
for (auto& a : tree[current]){
if (a == previous) continue;
dfs(current, a);
r += child[a] + 1;
}
child[current] = r;
d_root += r;
}