参考问题:Build tree array from flat array in javascript
这个答案已经发布,时间复杂度据说是O(nlogn)。但我很困惑为什么。因为如果我们将地图视为散列映射而不是散列映射中的查找操作需要O(1)时间,那么所提到的答案的时间复杂度应该是线性的,即O(n)。 我仍然不清楚javascript地图或对象查找需要恒定的时间或对数时间。
function list_to_tree(list) {
var map = {}, node, roots = [], i;
for (i = 0; i < list.length; i += 1) {
map[list[i].id] = i; // initialize the map
list[i].children = []; // initialize the children
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.parentId !== "0") {
// if you have dangling branches check that map[node.parentId] exists
list[map[node.parentId]].children.push(node);
} else {
roots.push(node);
}
}
return roots;
}
var entries = [
{
"id": "12",
"parentId": "0",
"text": "Man",
"level": "1"
}, { /*...*/ }
];
console.log(list_to_tree(entries));