javascript深度优先遍历(DFS)广度优先遍历(BFS)

对于下面这段html代码,要求打印出每个节点的标签名和类名:

 
123 sdsd 456

这是一个p标签

遍历后的结果:

javascript深度优先遍历(DFS)广度优先遍历(BFS)_第1张图片

 遍历过程:

javascript深度优先遍历(DFS)广度优先遍历(BFS)_第2张图片

代码:递归写法

function deepTraversal(node,nodeList){
    if(node){
        nodeList.push(node);
        var children = node.children;
        for(var i = 0;i < children.length;i++){
            deepTraversal(children[i],nodeList);
        }
    }
    return nodeList;
}
var root = document.getElementById('root');
console.log(deepTraversal(root,nodeList=[]));

非递归:

function deepTraversal(node) {  
    var nodeList = [];  
    if (node) {  
        var stack = [];  
        stack.push(node);  
        while (stack.length != 0) {  
            var childrenItem = stack.pop();  
            nodeList.push(childrenItem);  
            var childrenList = childrenItem.children;  
            for (var i = childrenList.length - 1; i >= 0; i--)  
                stack.push(childrenList[i]);  
        }  
    }    
    return nodeList;  
}   
var root = document.getElementById('root')
console.log(deepTraversal(root))

广度优先:

//3.广度优先遍历的递归写法
function wideTraversal(node){
    let nodes=[],i=0;
    if(node!=null){
        nodes.push(node);
        wideTraversal(node.nextElementSibling);
        node=nodes[i++];
        wideTraversal(node.firstElementChild);
    }
    return nodes;
}

//4.广度优先遍历的非递归写法
function wideTraversal(node){
    let nodes=[],i=0;
    while(node!=null){
        nodes.push(node);
        node=nodes[i++];
        let childrens=node.children;
        for(let i=0;i

 

你可能感兴趣的:(javascript深度优先遍历(DFS)广度优先遍历(BFS))