Skip to content

Instantly share code, notes, and snippets.

@fazeelanizam13
Created May 30, 2022 06:53
Show Gist options
  • Save fazeelanizam13/95baaab8e9aaa30f127d5216f57c5dfe to your computer and use it in GitHub Desktop.
Save fazeelanizam13/95baaab8e9aaa30f127d5216f57c5dfe to your computer and use it in GitHub Desktop.
Implementation of breadth-first search algorithm on a binary search tree in JavaScript
class Node {
// stores given value and points to nothing
constructor (value) {
this.value = value
this.left = null
this.right = null
}
}
class Tree {
// initially just has a root variable with null assigned
constructor () {
this.root = null
}
// helper functions
// starting from root, traverses through a tree/subtree and
// inserts new node depending on its value
traverseAndInsert = (root, node) => {
// if new node value less than root
if (node.value < root.value) {
// if left node null, make new node the left node
if (root.left === null) root.left = node
// else get traverseAndInsert to find the correct place in left subtree to insert new node
else this.traverseAndInsert(root.left, node)
// if new node value greater than root
} else {
// if right node null, make new node the right node
if (root.right === null) root.right = node
// else get traverseAndInsert to find the correct place in right subtree to insert new node
else this.traverseAndInsert(root.right, node)
}
}
// end of helper functions
// to insert nodes to tree
insert = value => {
// create new node with given value
let node = new Node(value)
// if root null, make new node the root
if (this.root === null) this.root = node
// if not, get traverseAndInsert to find the correct place to insert new node
else this.traverseAndInsert(this.root, node)
}
// -------- BFS ----------
traverse = root => {
// have a queue structure
// using an array for simplicity
let queue = []
if (root === null) return null
// enqueue root of tree
queue.push(root)
// keep dequeueing nodes you visit and enqueueing their children
while (queue.length > 0) {
// get value from front item of queue
console.log(queue[0].value)
// enqueue children
if (queue[0].left) queue.push(queue[0].left)
if (queue[0].right) queue.push(queue[0].right)
// dequeue front item
queue.shift()
}
}
}
// tests
// let tree = new Tree()
// tree.insert(7)
// tree.insert(24)
// tree.insert(9)
// tree.insert(36)
// tree.insert(21)
// tree.traverse(tree.root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment