关键词:树结构; 路径搜索;
树结构,根据叶子节点id获取从根节点到叶子节点的完整路径
数据示例
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: []}
]
},
]
};
查找函数
function getPathById(catalog, id, callback){
//定义变量保存当前结果路径
let temppath = [];
try {
function getNodePath(node) {
temppath.push(node.id);
//找到符合条件的节点,通过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]);
}
//当前节点的子节点遍历完依旧没找到,则删除路径中的该节点
temppath.pop();
} else {
//找到叶子节点时,删除路径当中的该叶子节点
temppath.pop();
}
}
getNodePath(catalog);
} catch (e) {
let result = temppath;
callback(result);
}
}
函数调用
getPathById(catalog, 10010202, res => {
let path = res.join('->');
console.log(path);
});
结果
1001->100102->10010202
参考资料
https://blog.csdn.net/weixin_40902181/article/details/102975297
网友评论