js—深度优先遍历(DFS)和广度优先遍历(BFS)


递归 深度优先

function deepSearch(node, nodeList = []) {
if(node) {
    const child = node.children;
    nodeList.push(node);
    for(let i=0;i){
        deepSearch(child[i], nodeList);
    }
}
return nodeList;
}
const nodeList = [];
const a = deepSearch(document.getElementById('root'), nodeList);

非递归 深度优先

function deepSearch1(node) {
const nodeList = [];
const stack = [];
if(node) {
    stack.push(node);
    while(stack.length) {
        const item = stack.pop();
        nodeList.push(item);
        for(let i = item.children.length -1;i>-1;i--){
            stack.push(item.children[i]);
        }
    }
}
return nodeList;
}

const a = deepSearch1(document.getElementById('root'));

递归 广度优先

const nodeList = [];
function breadthSearch(node, nodeList = []) {
if(!(node == null)) {
    nodeList.push(node);
    breadthSearch(node.nextElementSibling, nodeList);
    breadthSearch(node.firstElementChild, nodeList);
}
return nodeList;
}
const a = breadthSearch(document.getElementById('root'), nodeList);

非递归 广度优先

function breadthSearch1(node) {
const nodeList = [];
const queue = [];
if(node) {
    queue.unshift(node);
    while(queue.length) {
        const item = queue.shift();
        nodeList.push(item);
        for(let i = 0;i){
            queue.push(item.children[i]);
        }
    }
}
return nodeList;
}

const a = breadthSearch1(document.getElementById('root'));