33 lines
829 B
JavaScript
33 lines
829 B
JavaScript
|
// 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;
|
||
|
}
|
||
|
};
|
||
|
}
|