function Node(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(f);
a.childs.push(b);
b.childs.push(d);
b.childs.push(e);
// 深度搜索
function deepSearch(root, target) {
if (root == null) return false;
if (root.value == target) {
return true;
}
let result = false;
for (let i = 0; i < root.childs.length; i++) {
result |= deepSearch(root.childs[i], target);
}
return result ? true : false;
}
console.log(deepSearch(a, 'n'));
// 广度搜索
function bfs(roots, target) {
if (roots == null || roots.length == 0) {
return false;
}
let childs = [];
for (let i = 0; i < roots.length; i++) {
if (roots[i].value == target) {
return true;
} else {
childs = childs.concat(roots[i].childs);
}
}
return bfs(childs, target);
}
console.log(bfs([a], 'c'));
算法