diff --git a/Data Structures/bstAddElement.js b/Data Structures/bstAddElement.js new file mode 100644 index 0000000..5722665 --- /dev/null +++ b/Data Structures/bstAddElement.js @@ -0,0 +1,35 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/add-a-new-element-to-a-binary-search-tree + +var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2)); +function Node(value) { + this.value = value; + this.left = null; + this.right = null; +} +function BinarySearchTree() { + this.root = null; + // Only change code below this line + this.add = (item) => { + const newNode = new Node(item); + if (this.root === null) { + this.root = newNode; + } + let parentNode = null; + let nodeBranch = "left"; + let node = this.root; + while (node !== null) { + parentNode = node; + if (node.value == item) { + return null; + } else if (node.value < item) { + nodeBranch = "right"; + node = node.right; + } else { + nodeBranch = "left"; + node = node.left; + } + } + parentNode[nodeBranch] = newNode; + }; + // Only change code above this line +}