![](/img/trans.png)
[英]Error in Recursive Function Used For Inserting a Node in a Binary Tree in JavaScript
[英]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 從這棵樹中找到項目。 我正在使用遞歸函數來迭代樹及其子項,但它不會像我預期的那樣找到該項目。
它總是返回空值。 預計返回{id: 345, children:[]}
您需要使用允許在查找時短路的方法退出循環。
訪問節點但已經找到節點的問題是用后來的錯誤結果替換結果。 您需要在找到節點的情況下提前退出。
Array#some
允許迭代並在返回真實值時退出循環。 在這種情況下,結果是真實的。
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));
我們也可以對遞歸函數使用reduce方法
function findAllByKey(obj, keyToFind) {
return Object.entries(obj)
.reduce((acc, [key, value]) => (key === keyToFind)
? acc.concat(value)
: (typeof value === 'object' && value)
? acc.concat(findAllByKey(value, keyToFind))
: acc
, []) || [];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.