【发布时间】:2019-01-29 18:49:25
【问题描述】:
我正在尝试创建一棵树并计算它的高度。
map 数组在 for 循环中正确初始化,但 console.log(map+" this is map"); 显示
[object Object],[object Object],[object Object],[object Object],[object Object] this is map。我在
map[list[i]]["children"].push(node);
错误是TypeError: Cannot read property 'children' of undefined
这个怎么解决??
输入是 -
5
4 -1 4 1 1
第一行包含节点数????。第二行包含 ????整数 从 -1 到 ???? − 1 — 节点的父节点。如果其中第 ????-th 个 (0 ≤ ?????? ≤ ???? - 1) 为 -1,则节点 ????是根, 否则它是 ????-th 节点的父节点的从 0 开始的索引。保证只有一个根。 保证输入代表一棵树。
代码-
var readline = require('readline');
var input = [];
enter image description here
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.prompt();
rl.on('line', function (cmd) {
input.push(cmd);
});
rl.on('close', function (cmd) {
input=input[1].split(" ");
console.log(list_to_tree(input));
let tree1=list_to_tree(input);
console.log("this "+height(tree1));
process.exit(0);
});
function list_to_tree(list) {
var map = [], node, roots = [], i;
for(i=0;i<list.length;i++){
map.push({[i] :list[i],
children:[]
});
console.log(map);
}
console.log(map+" this is map");
for(i=0;i<list.length;i++){
node=map[i];
if(list[i]!==-1){
console.log(map[list[i]]);
map[list[i]]["children"].push(node);
}
else {
roots.push(node);}
}
return roots;
}
function height(tree){
if(tree===null){return 0;}
let h=0;
for(let x in tree){
for (let y in tree[x]["children"]){
h=Math.max(h,height(y));
}
return h+1;
}
}
【问题讨论】:
-
@PrashantGupta 我已经添加了输入格式,输出的 ss 是i.stack.imgur.com/gRNbm.jpg,你到底要的是哪个 json??
标签: javascript node.js data-structures tree