-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBreadthFirstSearch.js
More file actions
32 lines (28 loc) · 959 Bytes
/
BreadthFirstSearch.js
File metadata and controls
32 lines (28 loc) · 959 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
let BreadthFirstSearch = (tree, rootNode, searchValue) => {
// make a queue array
let queue = [];
// populate it with the node that will be the root of your search
queue.push(rootNode);
// search the queue until it is empty
while (queue.length > 0) {
// assign the top of the queue to variable currentNode
let currentNode = queue[0];
console.log("Current node is:" + currentNode.value);
// if currentNode is the node we're searching for, break & alert
if (currentNode.value === searchValue) {
console.log("Found it!");
return;
}
// if currentNode has a left child node, add it to the queue.
if (currentNode.left !== null) {
queue.push(tree[currentNode.left]);
}
// if currentNode has a right child node, add it to the queue.
if (currentNode.right !== null) {
queue.push(tree[currentNode.right]);
}
// remove the currentNode from the queue.
queue.shift();
}
console.log("Sorry, no such node found :(");
}