zoukankan      html  css  js  c++  java
  • 15.树的深度优先搜索和广度优先搜索代码实现(JavaScript版)

    树的深度优先搜索和广度优先搜索:

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    
    <body>
        <script>
            function Node(value) {
                this.value = value;
                this.childs = [];
            }
    
            var node1 = new Node("1");
            var node2 = new Node("2");
            var node3 = new Node("3");
            var node4 = new Node("4");
            var node5 = new Node("5");
            var node6 = new Node("6");
            var node7 = new Node("7");
            var node8 = new Node("8");
            var node9 = new Node("9");
            var node10 = new Node("10");
            var node11 = new Node("11");
            var node12 = new Node("12");
            var node13 = new Node("13");
    
            node1.childs = [node2, node3, node4];
            node2.childs = [node5, node6, node7];
            node3.childs = [node8, node9, node10];
            node4.childs = [node11, node12, node13];
    
    
            //树的广度优先搜索
            function breadthSearch(roots, target) {
                if (roots == null || roots.length == 0) return false;
                var child = [];
                for (var i = 0; i < roots.length; i++) {
                    if (roots[i].value == target) {
                        return true;
                    } else {
                        child = child.concat(roots[i].childs);
                    }
                }
                return breadthSearch(child, target);
            }
            //测试,树的广度搜索
            console.log(breadthSearch([node1], "14"));
    
            //树的深度优先搜索
            function deepSearch(root, target) {
                if (root == null) return false;
                if (root.value == target) return true;
                var isExist = false;
                for (var i = 0; i < root.childs.length; i++) {
                    isExist |= deepSearch(root.childs[i], target);
                }
                return isExist ? true : false;
            }
            //测试,树的深度搜索
            console.log(deepSearch(node1, "13"));
        </script>
    </body>
    
    </html>
    树的深度优先搜索和广度优先搜索
  • 相关阅读:
    Deep Learning ——Yann LeCun,Yoshua Bengio&Geoffrey Hinton
    numpy模块
    损失函数、正则化、优化
    最近邻分类器,K近邻分类器,线性分类器
    python json,pickle模块
    python os,sys模块
    python random模块
    到2030年,人工智能会发展成什么样?
    AI的偏见:机器就是绝对理性的么?
    5G和AI:现在和未来的互补技术
  • 原文地址:https://www.cnblogs.com/lanshanxiao/p/13210210.html
Copyright © 2011-2022 走看看