zoukankan      html  css  js  c++  java
  • 多叉树的深度优先和广度优先遍历

    多叉树的深度优先和广度优先遍历

    • 深度优先的思想比较常见,就是使用递归,没什么好说的。
    • 广度优先的思想,主要是需要借助一个队列,不停地将同一层级的子节点放入队列,然后依次从队列中取出执行。
    /**
     * var Node = {
     *    data: null,
     *    children: Array<Node>
     * }
     */
    function breadthFirstTraversal(node) {
        let nodeList = [node];
        while(nodeList.length > 0) {
            const current = nodeList.shift();
            console.log(current.data);
            
            if(current.children && current.children.length > 0) {
                nodeList.push(...current.children);
            }
        }
    }
    
    function depthFirstTraversal(node) {
        function traversal(node) {
            console.log(node.data);
            if(node.children && node.children.length > 0) {
                for(let i = 0;i < node.children.length;i++) {
                    traversal(node.children[i]);
                }
            }
        }
        traversal(node);
    }
    
    const node = {
        data: 1,
        children: [
            {
                data: 2,
                children: [
                    {
                        data: 3
                    }
                ]
            },
            {
                data: 4,
                children: [
                    {
                        data: 5,
                        children: [
                            {
                                data: 6
                            }
                        ]
                    }
                ]
            },
            {
                data: 7
            }
        ]
    }
    
    breadthFirstTraversal(node); // 1 2 4 7 3 5 6
    depthFirstTraversal(node); // 1 2 3 4 5 6 7
    
    • 记一次比较尴尬的面试,广度优先写不出来,比较憨批
  • 相关阅读:
    自定义动画(仿Win10加载动画)
    jquery 仿windows10菜单效果下载
    mac os+selenium2+Firefox驱动+python3
    mac os+selenium2+chrome驱动+python3
    mac 安装scrapy
    mac 查看系统位数
    ubuntu安装 mysqldb
    ubuntu安装常用软件
    scp 时出现permission denied
    ubuntu 安装git
  • 原文地址:https://www.cnblogs.com/aloneMing/p/15181363.html
Copyright © 2011-2022 走看看