From 48fd64b61f243f9a9549985362260d46674dd01c Mon Sep 17 00:00:00 2001 From: Manish Date: Mon, 4 Sep 2023 15:44:46 +1000 Subject: [PATCH] Data Structures: Delete a Node with One Child in a Binary Search Tree --- Data Structures/bstDeleteOneChildNode.js | 35 ++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Data Structures/bstDeleteOneChildNode.js diff --git a/Data Structures/bstDeleteOneChildNode.js b/Data Structures/bstDeleteOneChildNode.js new file mode 100644 index 0000000..caeb4fc --- /dev/null +++ b/Data Structures/bstDeleteOneChildNode.js @@ -0,0 +1,35 @@ +// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/delete-a-node-with-one-child-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; + let child = null; + if (node.left !== null && node.right === null) child = node.left; + else if (node.left === null && node.right !== null) child = node.right; + if (parent === null) this.root = child; + else if (parent.value < value) { + parent.right = child; + } else { + parent.left = child; + } + }; +}