diff --git a/src/binary-search-tree.js b/src/binary-search-tree.js index 262a838..4393adc 100644 --- a/src/binary-search-tree.js +++ b/src/binary-search-tree.js @@ -2,6 +2,8 @@ /* eslint-disable global-require */ /* eslint-disable no-unused-vars */ /* eslint-disable no-trailing-spaces */ +const Queue = require('./queue-helper'); + class BinarySearchTree { constructor(value) { this.value = value; @@ -12,18 +14,53 @@ class BinarySearchTree { // assigns it to either the left or right subtree, // depending on its value insert(value) { + const newNode = new BinarySearchTree(value); + if (value < this.value) { + if (!this.left) { + this.left = newNode; + } else { + this.left.insert(value); + } + } else if (value > this.value) { + if (!this.right) { + this.right = newNode; + } else { + this.right.insert(value); + } + } } // Checks the binary search tree for the input target // Can be written recursively or iteratively contains(target) { - + if (this.value === target) { + return true; + } + if (this.left) { + if (this.left.contains(target)) { + return true; + } + } + if (this.right) { + if (this.right.contains(target)) { + return true; + } + } + return false; } + // Traverses the tree in a depth-first manner, i.e. from top to bottom // Applies the given callback to each tree node in the process depthFirstForEach(cb) { - + cb(this.value); + if (this.left) { + this.left.depthFirstForEach(cb); + } + if (this.right) { + this.right.depthFirstForEach(cb); + } } + // Traverses the tree in a breadth-first manner, i.e. in layers, starting // at the root node, going down to the root node's children, and iterating // through all those nodes first before moving on to the next layer of nodes @@ -31,8 +68,19 @@ class BinarySearchTree { // You'll need the queue-helper file for this. Or could you roll your own queue // again. Whatever floats your boat. breadthFirstForEach(cb) { - + const queue = new Queue(); + queue.enqueue(this); + while (!queue.isEmpty()) { + const node = queue.dequeue(); + if (node.left) { + queue.enqueue(node.left); + } + if (node.right) { + queue.enqueue(node.right); + } + cb(node.value); + } } -} - + } + module.exports = BinarySearchTree; diff --git a/src/tree.js b/src/tree.js index b6b7908..dc002cf 100644 --- a/src/tree.js +++ b/src/tree.js @@ -7,13 +7,20 @@ class Tree { } // Adds a new Tree node with the input value to the current Tree node addChild(value) { - + const newChild = new Tree(value); + this.children.push(newChild); } // Checks this node's children to see if any of them matches the given value // Continues recursively until the value has been found or all of the children // have been checked contains(value) { - + if (this.value === value) return true; + for (let i = 0; i < this.children.length; i++) { + if (this.children[i].contains(value)) { + return true; + } + } + return false; } }