關(guān)鍵詞:樹結(jié)構(gòu); 路徑搜索;
樹結(jié)構(gòu)玫膀,根據(jù)葉子節(jié)點id獲取從根節(jié)點到葉子節(jié)點的完整路徑
數(shù)據(jù)示例
let catalog = {
id: 1001,
children: [
{
id: 100101,
children: [
{id: 10010101, children: []},
{id: 10010102, children: []},
]
},
{
id: 100102,
children: [
{id: 10010201, children: []},
{id: 10010202, children: []},
{id: 10010203, children: []}
]
},
]
};
查找函數(shù)
function getPathById(catalog, id, callback){
//定義變量保存當(dāng)前結(jié)果路徑
let temppath = [];
try {
function getNodePath(node) {
temppath.push(node.id);
//找到符合條件的節(jié)點佑颇,通過throw終止掉遞歸
if (node.id === id) {
throw ('GOT IT!');
}
if (node.children && node.children.length > 0) {
for (let i = 0; i < node.children.length; i++) {
getNodePath(node.children[i]);
}
//當(dāng)前節(jié)點的子節(jié)點遍歷完依舊沒找到镰惦,則刪除路徑中的該節(jié)點
temppath.pop();
} else {
//找到葉子節(jié)點時罚渐,刪除路徑當(dāng)中的該葉子節(jié)點
temppath.pop();
}
}
getNodePath(catalog);
} catch (e) {
let result = temppath;
callback(result);
}
}
函數(shù)調(diào)用
getPathById(catalog, 10010202, res => {
let path = res.join('->');
console.log(path);
});
結(jié)果
1001->100102->10010202
參考資料
https://blog.csdn.net/weixin_40902181/article/details/102975297