我正在尝试创建一棵树并计算它的高度。
map
数组在 for
循环中正确初始化,但 console.log(map+"this is map");
显示
[object Object],[object Object],[object Object],[object Object],[object Object]这是 map
。我在访问第二个 for 循环中的 Children 属性时遇到问题
map[list[i]]["children"].push(node);
错误是TypeError:无法读取未定义的属性“children”
如何解决这个问题?
输入是 -
5
4 -1 4 1 1
第一行包含 Node 数𝑛。第二行包含𝑛整数 从 −1 到 𝑛 − 1 — Node 的父 Node 。如果其中第 𝑖 (0 ≤ 𝑖 ≤ 𝑛 − 1) 为 -1,则 Node 𝑖 为根, 否则它是第 𝑖 个 Node 的父 Node 的从 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;
}
}
最佳答案
将“map”声明为对象数组。然后像这样使用。
map.push({node})
我也遇到过同样的问题,而且我确实喜欢这个。声明为对象数组的列表。
关于JavaScript-类型错误: Cannot read property 'children' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51984972/