From the course: Data Structures in JavaScript: Trees and Graphs
Unlock this course with a free trial
Join today to access over 25,600 courses taught by industry experts.
Breadth-first search implementation
From the course: Data Structures in JavaScript: Trees and Graphs
Breadth-first search implementation
- [Host] In the previous lesson, I explained the concept of breadth first search. In this lesson, we will implement BFS in JavaScript, breaking its logic step by step to see how it works. We'll write a function called breadth first search that searches for a target node. This function will take in two parameters, a root and the target and returns a Boolean of true if the target node exists in the tree or false otherwise. Let's first handle an edge case. If the root is null, we will immediately return false. Now, any line after this, we guarantee that the root is a binary tree, no type. Then we will create a queue and instantiate the root inside it. We now will set up a while loop to continue processing while the queue is not empty. We keep track of this condition by checking at the length of the queue is greater than zero. Inside the while loop, we will first DQ the node in the front and call it current, short for the current node. We check if the current node's value is a target. If…