From f74eb15489ef7953b464cbbd1b03dbaedc5a3691 Mon Sep 17 00:00:00 2001 From: Manish Date: Sun, 27 Aug 2023 16:21:19 +1000 Subject: [PATCH] Data Structures: Add a New Element to a Binary Search Tree --- Data Structures/bstAddElement.js | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Data Structures/bstAddElement.js 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 +}