How to realize breadth-first traversal by js
Editor to share with you how to achieve breadth-first traversal of js, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to know it!
1. The breadth first traverses the binary tree, that is, traversing according to the level.
2. Create a new queue, the root node joins the queue, dequeue and visit the queue head, and repeat steps 2 or 3 of the neighboring nodes not visited by the queue head until the queue is empty.
Example
Breadth-first traversal of a graph const graph = {0: [1,2], 1: [2], 2: [0,3], 3: [3],}; / / depth-first traversal of a graph const visited = new Set (); visited.add (2); const Q = [2]; const bfs = (n) = > {while (q.length) {const n = q.shift (); console.log (n) Graph.forEach ((c) = > {if (! visited.has (c)) {q.push (c); visited.add (c);}});}; bfs (2); / / 2031 is all the contents of the article "how to achieve breadth-first traversal in js". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!