gpt4 book ai didi

javascript - JavaScript 中嵌套对象结构的递归树搜索

转载 作者:行者123 更新时间:2023-12-03 07:21:15 25 4
gpt4 key购买 nike

我试图弄清楚如何递归地搜索此 JSON 对象中的节点。我尝试过一些东西但无法得到它:

var tree = {
"id": 1,
"label": "A",
"child": [
{
"id": 2,
"label": "B",
"child": [
{
"id": 5,
"label": "E",
"child": []
},
{
"id": 6,
"label": "F",
"child": []
},
{
"id": 7,
"label": "G",
"child": []
}
]
},
{
"id": 3,
"label": "C",
"child": []
},
{
"id": 4,
"label": "D",
"child": [
{
"id": 8,
"label": "H",
"child": []
},
{
"id": 9,
"label": "I",
"child": []
}
]
}
]
};

这是我的非工作解决方案,这可能是因为第一个节点只是一个值,而子节点位于数组中:

function scan(id, tree) {
if(tree.id == id) {
return tree.label;
}

if(tree.child == 0) {
return
}

return scan(tree.child);
};

最佳答案

您的代码只是缺少一个循环来检查 child 数组中节点的每个子节点。此递归函数将返回节点的 label 属性,如果树中不存在标签,则返回 undefined :

const search = (tree, target) => {
if (tree.id === target) {
return tree.label;
}

for (const child of tree.child) {
const found = search(child, target);

if (found) {
return found;
}
}
};

const tree = {"id":1,"label":"A","child":[{"id":2,"label":"B","child":[{"id":5,"label":"E","child":[]},{"id":6,"label":"F","child":[]},{"id":7,"label":"G","child":[]}]},{"id":3,"label":"C","child":[]},{"id":4,"label":"D","child":[{"id":8,"label":"H","child":[]},{"id":9,"label":"I","child":[]}]}]};

console.log(search(tree, 1));
console.log(search(tree, 6));
console.log(search(tree, 99));

您还可以使用显式堆栈迭代执行此操作,这不会导致堆栈溢出(但请注意,简写 stack.push(...curr.child); 可能会溢出参数由于扩展语法的原因,某些 JS 引擎的大小,因此对大量子数组使用显式循环):

const search = (tree, target) => {
for (const stack = [tree]; stack.length;) {
const curr = stack.pop();

if (curr.id === target) {
return curr.label;
}

stack.push(...curr.child);
}
};

const tree = {"id":1,"label":"A","child":[{"id":2,"label":"B","child":[{"id":5,"label":"E","child":[]},{"id":6,"label":"F","child":[]},{"id":7,"label":"G","child":[]}]},{"id":3,"label":"C","child":[]},{"id":4,"label":"D","child":[{"id":8,"label":"H","child":[]},{"id":9,"label":"I","child":[]}]}]};

for (let i = 0; ++i < 12; console.log(search(tree, i)));

更通用的设计将返回节点本身,并让调用者根据需要访问 .label 属性,或者以其他方式使用该对象。

请注意,JSON 纯粹是序列化(字符串化、原始)数据的字符串格式。一旦将 JSON 反序列化为 JavaScript 对象结构(如下所示),它就不再是 JSON。

关于javascript - JavaScript 中嵌套对象结构的递归树搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52066403/

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