I am faced with a map that visually represents a graph as follows:
Map(5) {
1 => [ 2, 3 ],
2 => [ 7, 8, 10 ],
3 => [ 4 ],
10 => [ 12 ],
4 => [ 11 ]
}
In addition, there's this specific class designed to generate a rooted tree:
class RootedTree {
constructor (data, ...descendants) {
this.data = data;
this.descendants = descendants;
}
}
The main objective at hand is to convert the given graph into a rooted tree based on a chosen root. Taking the example where 1 serves as the root, the desired output would be:
const RT = (...args) => new RootedTree(...args) // for simplification
// intended result:
RT(1, RT(2, RT(7), RT(8), RT(10, RT(12))), RT(3, RT(4, RT(11)), RT(5))
My current approach involves the following code snippet:
let local_descendants = []
const toRT = (root, node_map) => {
rt = new RootedTree(root)
if (node_map.get(root) !== undefined){
node_map.get(root).map((node) => toRT(node, node_map), local_descendants)
} else {
return null
}
return local_descendants
}
rt = new RootedTree(1, toRT(1, map))
However, upon execution, the toRT function appears to return an empty array. It seems like there might be some confusion regarding the handling of variables within the function. I'm currently stuck and looking for guidance on how to address this issue.