diff --git a/BinarySearchTree.js b/BinarySearchTree.js new file mode 100644 index 0000000000..b29b23cdda --- /dev/null +++ b/BinarySearchTree.js @@ -0,0 +1,49 @@ +// --- Directions +// 1) Implement the Node class to create +// a binary search tree. The constructor +// should initialize values 'data', 'left', +// and 'right'. +// 2) Implement the 'insert' method for the +// Node class. Insert should accept an argument +// 'data', then create an insert a new node +// at the appropriate location in the tree. +// 3) Implement the 'contains' method for the Node +// class. Contains should accept a 'data' argument +// and return the Node in the tree with the same value. +// If the value isn't in the tree return null. + +class Node { + constructor(data) { + this.data = data; + this.left = null; + this.right = null; + } + + insert(data) { + if (data < this.data && this.left) { + this.left.insert(data); + } else if (data < this.data) { + this.left = new Node(data); + } else if (data > this.data && this.right) { + this.right.insert(data); + } else if (data > this.data) { + this.right = new Node(data); + } + } + + contains(data) { + if (this.data === data) { + return this; + } + + if (this.data < data && this.right) { + return this.right.contains(data); + } else if (this.data > data && this.left) { + return this.left.contains(data); + } + + return null; + } +} + +module.exports = Node;
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: