Open dorseysen opened 5 years ago
// 2019-08-15:BFS
// 请写一个简单的广度优先搜索(BFS)实现过程
import { Tree } from './tree';
class BFS {
constructor (tree, target) {
this.tree = tree;
this.flag = true;
this.count = 0;
this.init(target);
}
init (target) {
this.flag && this.breathFirst(this.tree, target);
// console.log("this.count = " + this.count);
}
breathFirst (nodeList, target) {
let nextNodeList = [];
for(let item of nodeList) {
this.count ++;
if(item.id === target) {
// console.log(item.name);
this.name = item.name;
this.flag = false;
return;
}
if( !!item.children && item.children.length) {
nextNodeList.push(...item.children);
}
}
this.flag && nextNodeList.length && this.breathFirst(nextNodeList, target);
}
}
return new BFS(Tree, '1111').name;
请写一个简单的广度优先搜索(BFS)实现过程。
此处提供tree.js的树结构对象以供搜索。