Javascript 当树节点具有子树大小时,如何按索引返回树节点?
假设我有这段演示数据:Javascript 当树节点具有子树大小时,如何按索引返回树节点?,javascript,arrays,search,tree,Javascript,Arrays,Search,Tree,假设我有这段演示数据: { size: 100, type: 'container', list: [ { size: 30, type: 'container', list: [ { size: 10, type: 'leaf', list: [1,2,3,4,5,6,7,8,9,10] }, { size: 1
{
size: 100,
type: 'container',
list: [
{
size: 30,
type: 'container',
list: [
{
size: 10,
type: 'leaf',
list: [1,2,3,4,5,6,7,8,9,10]
},
{
size: 15,
type: 'leaf',
list: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
},
{
size: 25,
type: 'leaf',
list: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
}
]
},
{
size: 50,
type: 'container',
list: [
{
size: 20,
type: 'leaf',
list: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
},
{
size: 25,
type: 'leaf',
list: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
},
{
size: 25,
type: 'leaf',
list: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
}
,
{
size: 30,
type: 'leaf',
list: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30]
}
]
},
{
size: 20,
type: 'container',
list: [
{
size: 5,
type: 'leaf',
list: [1,2,3,4,5]
},
{
size: 15,
type: 'leaf',
list: [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
}
]
}
]
}
注意,我刚刚用整数填充了所谓的“叶”节点,以显示它们的数组位置。但它们可以用任何JavaScript对象(数组、对象、字符串、数字等)填充。叶节点最多可以有32个项目,但我认为这对这个问题并不重要。容器节点也只能有32个直接子节点
如何说getLeafContaining(tree,index)
,它将返回在全局索引中包含该项的叶以及相对索引。我之所以说“全局索引”,是因为这是叶节点的索引,如果你把所有的叶节点都看作是连续的
到目前为止,我所做的是:
const getleaftcontaining=(树,索引)=>{
如果(索引>树大小-1){
返回{node:null,索引:-1}
}
让节点=[树]
让startSize=0
a:
while(true){
b:
for(设i=0,n=nodes.length;i 如果(startSizeNo,这是不正确的,index“相对索引”是什么意思?奇怪的是,你没有在树上使用标准的递归方法相对索引是相对于最后一个叶的索引,它最多包含32项。
const getLeafContaining = (tree, index) => {
if (index < tree.size) {
if (node.type == 'leaf') {
return { node, index };
} else if (node.type == 'container') {
let before = 0
for (const node of nodes) {
const after = before + node.size;
if (index < after) {
return getLeafContaining(node, index - before);
}
before = after;
}
}
}
return { node: null, index: -1 }
}
for (const node of nodes) {
if (index < node.size) {
return getLeafContaining(node, index);
}
index -= node.size;
}