From 717829745a70d9a1d3b841d16e6573ee987df5eb Mon Sep 17 00:00:00 2001 From: Stephanie Brooks Date: Thu, 1 Feb 2018 18:54:35 -0600 Subject: [PATCH] BST still needs work --- src/binary-search-tree.js | 41 ++++++++++++++++++++++++++++++++++++--- src/tree.js | 9 +++++++-- 2 files changed, 45 insertions(+), 5 deletions(-) diff --git a/src/binary-search-tree.js b/src/binary-search-tree.js index 262a838..b3ea41b 100644 --- a/src/binary-search-tree.js +++ b/src/binary-search-tree.js @@ -2,28 +2,64 @@ /* eslint-disable global-require */ /* eslint-disable no-unused-vars */ /* eslint-disable no-trailing-spaces */ +/*eslint-disable*/ +const Queue = require('./queue-helper'); class BinarySearchTree { constructor(value) { this.value = value; this.left = null; this.right = null; } + // Wraps the input value in a new BinarySearchTree and // assigns it to either the left or right subtree, // depending on its value insert(value) { - + if(value <= this.value){ + if (this.left === null){ + this.left = new BinarySearchTree(value); + }else { + this.left.insert(value); + } + } else if(value > this.value){ + if (!this.right){ + this.right = new BinarySearchTree(value); + } else { + this.right.insert(value); + } + } } // Checks the binary search tree for the input target // Can be written recursively or iteratively contains(target) { + let node = this; + while(node !== null){ + if (target === node.value) return true; + if (target <= node.value){ + node = node.right; + } else { + node = node.left; + } + } + 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) { + if (node) { + cb(node.value); + if (node.left) { + this.depthFirstForEach(node.left, cb); + } + if (node.right) { + this.depthFirstForEach(node.right, 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 +67,7 @@ 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) { - + } } - module.exports = BinarySearchTree; diff --git a/src/tree.js b/src/tree.js index b6b7908..2b903a4 100644 --- a/src/tree.js +++ b/src/tree.js @@ -7,13 +7,18 @@ class Tree { } // Adds a new Tree node with the input value to the current Tree node addChild(value) { - + const newNode = new Tree(value); + this.children.push(newNode); } // 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; } }