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>