Open dorseysen opened 5 years ago
// 2019-08-16:DFS
// 请写一个简单的深度优先搜索(DFS)实现过程(与上题BFS一样实现对同一Tree的搜索)
console.log(" ============== DFS =================== ");
class DFS {
constructor (tree, target) {
this.tree = tree;
this.count = 0;
this.flag = true;
this.init(target);
}
init (target) {
this.tree.forEach(item => {
// 可以尝试一下这里的目标id传入11112跟12的区别,可以很简单的看出11112的this.count更小,深度优先
// this.flag && this.deepFirst(item, "11112");
this.flag && this.deepFirst(item, target);
});
// console.log("this.count = " + this.count);
}
deepFirst (node, target) {
this.count ++;
if(node.id === target) {
// console.log(node.name);
this.name = node.name;
this.flag = false;
return;
}
if( !!node.children && !!node.children.length ) {
node.children.forEach(item => this.flag && this.deepFirst(item, target));
}
}
}
return new DFS(JSON.parse(JSON.stringify($state.Tree)), '1111').name;
请写一个简单的深度优先搜索(DFS)实现过程(与上题BFS一样实现对同一Tree的搜索)