何为广度优先搜搜
如上图 假如进行广度优先搜索的顺序为
A — C — B —F — G — D — E
广度优先搜索,同一行的搜索完后再去搜索下一行
代码实现广度优先搜索
class Node {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
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")
let g = new Node("g")
a.left = c;
c.left = f;
b.left = d;
a.right = b;
b.right = e;
c.right = g;
/**
* 广度优先搜搜
* @param {*} rootList 查询列表
* @param {*} target 目标值
* @returns
*/
function f1(rootList , target){
if(rootList == null || rootList.length == 0) return false;
var childList = []
for (let i = 0; i < rootList.length; i++) {
if(rootList[i].value!= null) return false;
if(rootList[i] != null && rootList[i].value == target){
return true;
}else{
childList.push(rootList[i].left)
childList.push(rootList[i].right)
}
}
return f1(childList , target)
}
console.log(f1([a],"o"))