【算法】树的深度优先搜索和广度优先搜索

152 阅读1分钟

一、树的深度优先搜索

function Node(value) {
    this.value = value;
    this.child = [];
}
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.child = [b, c, d];
b.child = [e, f];

function deepSearch(node, target) {
    if (node == null) return false;
    if (node.value == target) return true;
    let result = false;
    for (let i = 0; i < node.childs.length; i ++) {
        result |= deepSearch(node.childs[i], target)
    }
    return result ? true : false;
}
console.log(deepSearch(a, F"))

二、树的广度优先搜索

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)
            console.log(childs)
        }
    }
    return bfs(childs, target);
}
console.log(bfs([a], "E"))