美文网首页
浅谈JavaScript中树的深度优先遍历和广度优先遍历

浅谈JavaScript中树的深度优先遍历和广度优先遍历

作者: 小豆soybean | 来源:发表于2018-09-25 20:52 被阅读0次

    原文链接:https://blog.csdn.net/zhouziyu2011/article/details/62236006
    1、深度优先遍历的递归写法

    function deepTraversal(node) {
        var nodes = [];
        if (node != null) {  
                nodes.push(node);  
                var children = node.children;  
                for (var i = 0; i < children.length; i++)  
                    deepTraversal(children[i]);  
            }  
        return nodes;
    }
    
    

    2、深度优先遍历的非递归写法

    function deepTraversal(node) {
        var nodes = [];
        if (node != null) {
            var stack = [];
            stack.push(node);
            while (stack.length != 0) {
                var item = stack.pop();
                nodes.push(item);
                var children = item.children;
                for (var i = children.length - 1; i >= 0; i--)
                    stack.push(children[i]);
            }
        }  
        return nodes;
    }
    
    

    3.广度优先遍历的非递归写法

    function wideTraversal(selectNode) {
        var nodes = [];
        if (selectNode != null) {
            var queue = [];
            queue.unshift(selectNode);
            while (queue.length != 0) {
                var item = queue.shift();
                nodes.push(item);
                var children = item.children;
                for (var i = 0; i < children.length; i++)
                    queue.push(children[i]);
            }
        }
        return nodes;
    }
    
    

    相关文章

      网友评论

          本文标题:浅谈JavaScript中树的深度优先遍历和广度优先遍历

          本文链接:https://www.haomeiwen.com/subject/rwqroftx.html