gpt4 book ai didi

javascript - 一维数组转化为二叉树

转载 作者:行者123 更新时间:2023-11-27 23:39:28 29 4
gpt4 key购买 nike

 nodeArray = [  3,  3,  7,   6,   6,   7,    15,    10,   10,    14,    13,    13,    14,    15,    23,    18,    18,    22,    21,    21,    22,    23,    0  ];

nodes = [];
links = [];

function left(i) {
return 2*i + 1;
}
function right(i) {
return 2*i + 2;
}
function parent(i) {
console.log("Parent =" + (i-1)/2);
return (i-1)/2;
}

var index = 0;
do{
if (index === 0) {
var node = {
'value': nodeArray[index],
'child1_index': left(index),
'child1_value': nodeArray[left(index)],
'child2_index': right(index),
'child2_value': nodeArray[right(index)],
'parent_index' : 'null',
'parent_value' : 'null'
};
} else {
var node = {
'value': nodeArray[index],
'child1_index': left(index),
'child1_value': nodeArray[left(index)],
'child2_index': right(index),
'child2_value': nodeArray[right(index)],
'parent_index' :parent(index),
'parent_value' : nodeArray[parent(index)],
'index' : index
};
}
nodes.push(node);
index++;
} while (index != nodeArray.length)
console.log(nodes);

我编写了上面的代码,以便将来使用 d3.js 库将其转换为二叉树,不幸的是我所有的父节点值(显然是由任何节点 (index -1 )/ 2 给出的。给出的数字如 5.5 等是索引的一半或者其他东西。这显然不起作用。有些节点给出完整的整数,有些则不给出。

我的节点对象之一的示例控制台输出。看起来不错

Node1:
parent_index:0
parent_value:3

其他节点对象的示例。看起来不对的是

Node2:
parent_index:0.5
parent_value:undefined

如果有人感兴趣,这里有一个 jsfiddle http://jsfiddle.net/mryfw095/5/

最佳答案

我认为您只是希望您的 parent 函数向下舍入。

function  parent(i) {
console.log("Parent =" + Math.floor((i-1)/2));
return Math.floor((i-1)/2);
}

关于javascript - 一维数组转化为二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33826619/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com