关于DOM节点的深度优先和广度优先遍历

HTML的树形结构如上

深度优先遍历

对于树的深度优先遍历,执行结果应该如下:


采用递归方式
 var arr=[];
    //深度优先
    function traversalDFSDOM (rootDom) {
        if(!rootDom)return;
        if(rootDom.children.length==0){
            arr.push(rootDom)//没有孩子节点,表示是个叶子节点,将节点push到数组中
            return;
        }
        arr.push(rootDom)//非孩子节点,在每次遍历它的孩子节点之前先把它push到数组中
        for(var i=0;i<rootDom.children.length;i++){
            traversalDFSDOM(rootDom.children[i])//递归调用
        }

    }

结果如下

(script标签写在body外面,但是执行的时候浏览器会把它放到body中,变成最后一个元素)

采用非递归的方式
 //深度优先非递归
    function traversalDFSDOM(rootDom) {
        if(!rootDom)return;
        var stack=[]
        var node = rootDom;
        while(node!=null){
            arr.push(node);
            if(node.children.length>=0){
                for(let i=node.children.length-1;i>=0;i--)
                    stack.unshift(node.children[i]);
            }
            node = stack.shift()
        }
    }
    traversalDFSDOM(bodyDom)

非递归主要采取模拟队列的方法过程:


以此类推,需要注意的是i的循环需要从node.children.length-1开始到0

广度优先遍历

对于DOM树的广度优先遍历的结果应该如下
采用递归方式
var stack=[bodyDom];//bodyDom是遍历的根节点
    function traversalBFSDOM (count) {
        count = count || 0;
        if (stack[count]) {
            var children = stack[count].children;
            for (let i = 0; i < children.length; i++) {
                stack.push(children[i]);
            }
            traversalBFSDOM(++count)
        }
    }
traversalBFSDOM(0)
采用非递归方式
    function traversalBFSDOM (rootDom) {
        if(!rootDom)return;
        arr.push(rootDom)
        var queue = [rootDom];
        while(queue.length){
            var node = queue.shift();
            if(!node.children.length){
                continue;
            }
            for(var i=0;i<node.children.length;i++){
                arr.push(node.children[i]);
                queue.push(node.children[i]);
            }
        }
    }

主要采用先进先出的思想,依次遍历每个节点下的孩子节点。

运行结果如下:


学习是个过程,学会深入学习

祝自己生日快乐,感恩生活!

猜你喜欢

转载自blog.csdn.net/LXY224/article/details/79823669