From c37135f9acfe10236b0911899d5365f7c95b41fd Mon Sep 17 00:00:00 2001 From: Manish Date: Sun, 3 Sep 2023 14:49:51 +1000 Subject: [PATCH] Data Structures: Delete a Leaf Node in a Binary Search Tree --- Data Structures/bstDeleteLeafNode.js | 32 ++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Data Structures/bstDeleteLeafNode.js diff --git a/Data Structures/bstDeleteLeafNode.js b/Data Structures/bstDeleteLeafNode.js new file mode 100644 index 0000000..d8a2ef2 --- /dev/null +++ b/Data Structures/bstDeleteLeafNode.js @@ -0,0 +1,32 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/delete-a-leaf-node-in-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.remove = (value) => { + let parent = null; + let node = this.root; + while (node !== null && node.value !== value) { + parent = node; + if (node.value < value) { + node = node.right; + } else { + node = node.left; + } + } + if (node === null) return null; + if (parent === null) this.root = null; + else if (parent.value < value) { + parent.right = null; + } else { + parent.left = null; + } + }; +}