BFS in JavaScript (Data Structures)

Nilesh Saini
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.

Photo by Evgeni Tcherkasski on Unsplash

Pseudocode:

  1. Create a queue (this can be an array) and a variable array to store the values of nodes visited.
  2. Place the root node in the queue.
  3. 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)

--

--

Nilesh Saini
Nilesh Saini

Written by Nilesh Saini

Web Developer/ Front-end engineer who loves solving Rubik's Cube

No responses yet