我有一个通用的树类:myTree = new Tree(string), appendChildNode(node), createChildNode(string), myTree.print()个函数和myTree.name, myTree.children个等属性.
我还有一个多重映射,其中包含我想要分解并放入树对象中的数据.假设数据中没有圆圈.我的 idea 是让递归构建子分支.For some reason the recursion does not work and I cannot figure out why.在forEach内部返回给我一个"未定义的"
我的多重映射:
aaaa -> [b, c, d]
c -> [f]
f -> [g]
r -> [p]
因此,我得出的"aaaa"树应该是:
aaaa
b c d
f
g
我的主要功能:
myMultiMap ... <multimap defined here>
myTree = new Tree('End2End') // my tree object
// lets just pick the 'aaaa' to start with
myMultiMap.get('aaaa').forEach((entry) => {
newNode = new Tree(entry)
myTree.appendChildNode(recurse(newNode))
})
// show the tree after it was built
myTree.print()
递归函数
function recurse (node) {
// if the element is in the multimap, it has one or more children
if(myMultiMap.has(node.name)) {
// iterate through all children of the node in the multimap
myMultiMap.get(node.name).forEach((child) => {
// build a new node from the child
newChildnode = new Tree(child);
// build a subtree recursively, since this child could have children itself
return node.appendChildNode(recurse(newChildnode))
})
// if the node is not in the multimap, thus it has no children, so just return the node
} else {
return node
}
}
信息:我拿了这个树实现:https://github.com/beforesemicolon/tutorials-files/blob/master/tree-generic.js