I am working on sum of distance in tree
I tried to come up with my own solution, but got a LTE. I realised that I need to add a cache for the solution.
Here is my code
/**
* @param {number} n
* @param {number[][]} edges
* @return {number[]}
*/
var sumOfDistancesInTree = function(n, edges) {
// * g: graph
const graph = {};
let res = [];
let cache = {};
// * g: build graph
for(let i=0; i<edges.length; ++i) {
const ind1 = parseInt(edges[i][0]);
const ind2 = parseInt(edges[i][1]);
graph[ind1] = graph[ind1] || [];
graph[ind1].push(ind2);
graph[ind2] = graph[ind2] || [];
graph[ind2].push(ind1);
}
const recur = (origNode, parent, node, dist) => {
// if(cache[?]) {
// return cache[?]
// }
const arr = graph[node];
let sum = dist;
for(let i=0; i<arr?.length; ++i) {
const childnode = arr[i];
if(parent === childnode) {
continue;
}
const tmp = recur(origNode, node, childnode, dist+1);
sum = sum + tmp;
}
// * g: try to add cache, but not sure what should be the cache index
//cache[?] = sum;
return sum;
}
// * g: graph is done
for(let i=0; i<n; ++i) {
const out = recur(i, i, i, 0);
res.push(out);
}
return res;
};
The normal cache pattern is we cached the result at the end of func. On top, if we see cache value match, then we return cache value.
I am not sure what should be the cache index here.
I understand that start point to a particular point can go forward and backward, hence cache index can be start_pt + ‘‘ + end_point (forward) AND end_point + ‘‘ + start_pt (backward), to cache a particular path, but I am not able to fit to the cache pattern in the code above.
test case too big, cannot post here.