Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use depth first traversal and breadth first traversal algorithm in JavaScript

Shulou Source: shulou.com Published: 2022-05-31 11:48:03 09月28日 Update

This article mainly introduces "how to use depth-first traversal and breadth-first traversal algorithm in JavaScript". In daily operation, I believe that many people have doubts about how to use depth-first traversal and breadth-first traversal algorithm in JavaScript. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "depth-first traversal and breadth-first traversal algorithm in JavaScript". Next, please follow the editor to study!

The details are as follows:

1. Recursive method of depth-first traversal

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; iMel -) stack.push (childrens [I]);}} return nodes;}

3. The recursive method of breadth-first traversal:

Error report: Maximum call stack size exceeded (…)

Function wideTraversal (node) {var nodes = []; var I = 0; if (! (node = = null)) {nodes.push (node); wideTraversal (node.nextElementSibling); node = nodes [iTunes +]; wideTraversal (node.firstElementChild);} return nodes;}

4. Non-recursive writing method of breadth-first traversal.

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; iTunes +) queue.push (childrens [I]);} return nodes At this point, the study on "how to use depth-first traversal and breadth-first traversal algorithm in JavaScript" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Breadth depth algorithm writing recursion learning more help practical next articles methods theories knowledge articles websites materials follow questions easy to use Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Docker Shulou Technology Xiaomi Linux