BFS in JavaScript (Data Structures)
2 min readMay 8, 2022
Short and Precise Js code to do Breadth-first Search in a BST
Note: This is the continuation of the binary search tree article. To see the code of BST click here.
Pseudocode:
- Create a queue (this can be an array) and a variable array to store the values of nodes visited.
- Place the root node in the queue.
- Loop as long as there is anything in the queue.
- Dequeue a node from the queue and push the value of the node into the variable array that stores the nodes.
- If there is a left property on the node dequeued, add it to the queue.
- If there is a right property on the node dequeued, add it to the queue.
4. Return the variable array that stores the values.
Note: In the above code in the while loop we use queue.length
- If we do while(queue) then, when our queue is empty it will still be a truthy value and the loop will not terminate.
- It happens because,![] is falsy value (! empty array) and [] is truthy value (empty array)
More Useful Articles: