【发布时间】:2018-01-30 14:42:26
【问题描述】:
给定这样的结构:
var node = { children: [] }
也就是说:
- 它只有
children属性。 - 没有
parent属性。 - 没有
nextSibling属性。
如何使用自上而下的方法构建包含所有叶节点路径的平面数组列表:
- 该算法不使用任何辅助方法,只使用纯 JavaScript。
- 算法在从顶部遍历树时构建数组。
所以这里是一个示例数据:
var node = {
item: 1,
children: [
{
item: 2,
children: [
{
item: 3,
children: [
{
item: 4,
children: []
},
{
item: 5,
children: []
},
{
item: 6,
children: [
{
item: 7,
children: []
},
{
item: 8,
children: []
},
{
item: 9,
children: []
}
]
}
]
},
{
item: 10,
children: [
{
item: 11,
children: []
},
{
item: 12,
children: [
{
item: 13,
children: []
},
{
item: 14,
children: []
}
]
}
]
}
]
}
]
}
并且函数应该返回:
[
[1, 2, 3, 4],
[1, 2, 3, 5],
[1, 2, 3, 6, 7],
[1, 2, 3, 6, 8],
[1, 2, 3, 6, 9],
[1, 2, 10, 11],
[1, 2, 10, 12, 13],
[1, 2, 10, 12, 14]
]
到目前为止,我的尝试是:
function aggregateNodes(node) {
var stack = [node]
var array = []
while (stack.length) {
var node = stack.pop()
array.push(node.item)
node.children.forEach(function(child){
stack.push(child)
})
}
return array
}
function aggregateNodesRecursive(node) {
var array = [node.item]
node.children.forEach(function(child){
array.push(child.item)
child.children.forEach(function(confusedNow){
array.push(confusedNow.item)
aggregateNodesRecursive(confusedNow)
})
})
return array
}
【问题讨论】:
-
请添加您的尝试。
-
闻起来像作业
-
添加了我的尝试。不是作业哈哈
标签: javascript arrays combinations