const getPathById = (list,id) => {
const root = {
val:{
id:'',
children:list,
},
next:null,
path:[]
}
// 将队列的头和尾指向节点
let head = root , tail = root ;
while(head){
const {val,path} = head;
// 如果当前节点命中则返回path
if(val.id == id){
return [...path,val].slice(1);
}
if(val.children && val.children.length){
// 添加队列里面
val.children.forEach(item=>{
tail.next = {
val:item,
next:null,
path:[...path,val]
}
tail = tail.next;
})
}
head = head.next;
}
return [];
}
const list = [
{
id:1,
children:[
{
id:2,
children:[
{
id:4
},
{
id:5
}
]
},
{
id:3,
children:[
{
id:6
},
{
id:7
}
]
}
]
}
]
console.log(getPathById(list,7));
非递归遍历树找到某个节点的路径(队列、链表)
最新推荐文章于 2024-08-17 16:47:39 发布