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

版权声明:转载可不可以关注一下我呀 ^_^ https://blog.csdn.net/qq_41720311/article/details/84451737

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

 <div id='root'>
        <span>123
            <a href="#">
                sdsd
            </a>
            <div>sdsd<a>这是一个a标签</a></div>
        </span>
        <span>456
            <p>这是一个p标签</p>
        </span>
    </div>

遍历后的结果:

 遍历过程:

代码:递归写法

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<childrens.length;i++){
            nodes.push(childrens[i]);
        }
    }
    return nodes;
}

猜你喜欢

转载自blog.csdn.net/qq_41720311/article/details/84451737