场景:给出一个节点树,根据id找出对应的节点
节点树:
let tree = {
id: 1,
children: [
{
id: 2,
children: [
{id: 3},
{
id: 5,
children: [
{id: 6}
]
},
null
]
},
{
id: 4
},
null
]
}
// 写一个方法
function getNode(root, id) {
// 方法
}
console.log('1===>', getNode(tree, 1))
console.log('2===>', getNode(tree, 2))
console.log('3===>', getNode(tree, 3))
console.log('4===>', getNode(tree, 4))
console.log('5===>', getNode(tree, 5))
console.log('6===>', getNode(tree, 6))
console.log('10===>', getNode(tree, 10))
思路一:根据把它变成数组,然后用数组的思维去遍历数组找出对应的节点
function getNode(root, id) {
let arr = [root]
let res = null
while(arr.length){
let o = arr.pop()
if(o && o.id == id){
res = o
break
} else if(o && o.children && o.children.length ) {
arr.push(...o.children)
}
}
return res
}
思路二:利用递归的思路:
function getNode(root, id) {
let resultNode = null;
findNode(root, id);
function findNode(root, id){
if(!!root) {
let type = Object.prototype.toString.call(root);
if(type === '[object Object]') {
if(root.id && root.id === id) {
resultNode = root
} else {
let node = root.children || null
findNode(node, id);
}
}else if(type === '[object Array]') {
let needNode = root.find(i=> !!i === true && i.id === id);
if(!!needNode) {
resultNode = needNode;
} else {
if(root.length) {
root.forEach(item=>{
if(item && item.children) {
let node = item.children
if(node && node.length){
findNode(node, id);
}
}
})
}
}
}
}
}
return resultNode;
}
综合来讲: 第一种方式会比较好些,代码简洁,性能也比较高。