在树形数据中查找指定的值
数据为
let tree =[{
id: 1,
alue: 'A',
children:[
{
id: 2,
value: 'B',
children: [
{
id: 4,
value: 'D',
children: [
{ id: 8, value: 'H', children: [] },
{ id: 9, value: 'I', children: [] },
],
},
{ id: 5, value: 'E', children: [] },
],
},
{
id: 3,
value: 'C',
children: [
{ id: 6, value: 'F', children: [{ id: 10, value: 'J', children: [] }] },
{ id: 7, value: 'G', children: [] },
],
},
]
}]
1递归实现
function findValue(tree, e) {
let res = 0
function find(tree, e) {
// if (tree.length === 0) return
for (let i = 0; i < tree.length; i++) {
if (tree[i].value === e) {
res = tree[i].id
// console.log(res)
return tree[i].id
}
find(tree[i].children, e)
}
return res
}
return find(tree, e)
}
console.log(findValue(tree, 'G'))// 7
2 栈方法
将整个数据看为一棵二叉树 ,最外层为跟节点,采用深度遍历的方法,依次取出节点,判断节点是否有要查找的值,若没有将该节点的子节点入栈,在下一次循环中取出来执行相同操作, 参考 链接:juejin.cn/post/704988…
function DFSTest(tree, e) {
let stack = tree
while (stack.length) {
let node = stack.pop()
if (node.value === e) {
return node.id
}
if (node.children && node.children.length) {
stack.push(...node.children)
}
}
}
console.log(DFSTest(tree, 'J'))// 10