树的广度优先搜索
简介
树的广度优先搜索,先从根节点开始,逐层遍历所有节点,直到遍历完整棵树。
实现方法
也是数组操作,较简单
class Node {
constructor(value) {
this.value = value
this.childs = []
}
}
let a = new Node('a')
let b = new Node('b')
let c = new Node('c')
let d = new Node('d')
let e = new Node('e')
let f = new Node('f')
a.childs.push(c)
a.childs.push(b)
c.childs.push(f)
b.childs.push(d)
b.childs.push(e)
function bfs(roots, target) {
if (roots == null || roots.length === 0) return false
for (let i = 0; i < roots.length; i++) {
if (roots[i].value === target) return true
if (bfs(roots[i].childs, target)) return true
return false
}
}
console.log(bfs([a], 'ff'))