Java从树中找到具有递归功能的节点 [英] Javascript find node from tree with recursive function
问题描述
我有这样的 JavaScript
树数据.
const tree = {
children:[
{id: 10, children: [{id: 34, children:[]}, {id: 35, children:[]}, {id: 36, children:[]}]},
{id: 10,
children: [
{id: 34, children:[
{id: 345, children:[]}
]},
{id: 35, children:[]},
{id: 36, children:[]}
]
},
{id: 11, children: [{id: 30, children:[]}, {id: 33, children:[]}, {id: 3109, children:[]}]}
],
id: 45
}
const getByID = (tree, id) => {
let result = null
if (id === tree.id) {
return tree
} else {
if(tree.children){
tree.children.forEach( node=> {
result = getByID(node, id)
})
}
return result
}
}
const find345 = getByID(tree, 345)
console.log(find345)
我试图从这棵树中按ID查找项目.我使用递归函数来迭代树及其子对象,但无法按我的期望找到该项目.
I was try to find item by its id from this tree. im using recursive function to iterate the tree and its children, but it wont find the item as i expected.
它总是返回null.预期返回 {id:345,子代:[]}
its always return null. expected to return {id: 345, children:[]}
推荐答案
您需要使用允许在查找时发生短路的方法来退出循环.
You need to exit the loop by using a method which allows a short circuit on find.
访问节点但已找到该节点的问题是用后来的错误结果替换结果.您需要使用找到的节点尽早退出.
The problem with visiting nodes but already found the node, is the replacement of the result with a later wrong result. You need to exit early with a found node.
Array#some
允许迭代并退出循环(如果返回了truty值).在这种情况下,结果是真实的.
Array#some
allows to iterate and to exit the loop if a truty value is returned. In this case the result is truthy on find.
const tree = { children: [{ id: 10, children: [{ id: 34, children: [] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 10, children: [{ id: 34, children: [{ id: 345, children: [] }] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 11, children: [{ id: 30, children: [] }, { id: 33, children: [] }, { id: 3109, children: [] }] }], id: 45 };
const getByID = (tree, id) => {
let result = null
if (id === tree.id) {
return tree
} else {
if(tree.children){
tree.children.some(node => result = getByID(node, id));
// ^^^^ exit if found
// ^^^^^^^^^^^^^^^^^^^^^^^^^^ return & assign
}
return result;
}
}
const find345 = getByID(tree, 345)
console.log(find345)
短一点
var tree = { children: [{ id: 10, children: [{ id: 34, children: [] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 10, children: [{ id: 34, children: [{ id: 345, children: [] }] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 11, children: [{ id: 30, children: [] }, { id: 33, children: [] }, { id: 3109, children: [] }] }], id: 45 },
getByID = (tree, id) => {
var temp;
return tree.id === id
? tree
: (tree.children || []).some(o => temp = getByID(o, id)) && temp;
};
console.log(getByID(tree, 345));
这篇关于Java从树中找到具有递归功能的节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!