二叉树的深度优先搜索代码实现(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.left = null; this.right = null; } var nodeA = new Node("a"); var nodeB = new Node("b"); var nodeC = new Node("c"); var nodeD = new Node("d"); var nodeE = new Node("e"); var nodeF = new Node("f"); var nodeG = new Node("g"); nodeA.left = nodeB; nodeA.right = nodeC; nodeB.left = nodeD; nodeB.right = nodeE; nodeC.left = nodeF; nodeC.right = nodeG; function deepSort(root, target) { //深度搜索二叉树 if (root == null) return false; if (root.value == target) return true; var left = deepSort(root.left, target); //搜索左子树 var right = deepSort(root.right, target); //搜索右子树 return left || right; //target是否在左右子树里 } console.log(deepSort(nodeA, "g")); </script> </body> </html>
二叉树深度优先搜索
二叉树的广度优先搜索代码实现(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.left = null; this.right = null; } var nodeA = new Node("a"); var nodeB = new Node("b"); var nodeC = new Node("c"); var nodeD = new Node("d"); var nodeE = new Node("e"); var nodeF = new Node("f"); var nodeG = new Node("g"); nodeA.left = nodeB; nodeA.right = nodeC; nodeB.left = nodeD; nodeB.right = nodeE; nodeC.left = nodeF; nodeC.right = nodeG; function breadthSort(rootList, target) { if (rootList == null || rootList.length == 0) return false; var childList = []; //存放下一层的所有子节点 for (var i = 0; i < rootList.length; i++) {//依次遍历所有节点 if (rootList[i].value == target) { return true; } else { childList.push(rootList[i].left);//把节点的左子节点放入 childList.push(rootList[i].right);//把节点的右子节点放入 } } return breadthSort(childList, target);//在下一层节点中继续搜索 } console.log(breadthSort([nodeA], "g")); </script> </body> </html>
二叉树的广度优先搜索
1.《6.二叉树的深度优先搜索和广度优先搜索代码实现(JavaScript版)》援引自互联网,旨在传递更多网络信息知识,仅代表作者本人观点,与本网站无关,侵删请联系页脚下方联系方式。
2.《6.二叉树的深度优先搜索和广度优先搜索代码实现(JavaScript版)》仅供读者参考,本网站未对该内容进行证实,对其原创性、真实性、完整性、及时性不作任何保证。
3.文章转载时请保留本站内容来源地址,https://www.cxvn.com/study/26725.html