I am struggling to convert the JS recursive function below into a a trampoline function(s) in order to avoid maxing out the call stack with deep nodes.
It returns an array of all children nodes from the initial root node passed in. Note, list is a Map used to lookup the children of the current node for the next recursion iteration.
const getRootSet = (nodeId, list) => {
let results = [];
const node = list.get(nodeId);
if (node && node.children.size > 0) {
results.push(node.nodeId);
node.children.forEach((value, key) => {
results = results.concat(getRootSet(list.get(key).nodeId, list) );
});
}
if(node && node.children.size === 0)
{
//add last child node
results.push(node.nodeId);
}
return results;
}
How do I setup the trampoline structure in order to build the array of nodes to return at the end?
Sample data:
child, parent,
111111, 222222,
000000, 111111,
060270, 964240,
041342, 964240,
024367, 964240,
052643, 964240,
083020, 060270,
024367, 961758,
024367, 964264,
060270, 024367,
060270, 964240,
123456, 789100,
345678, 789100,