What is your hint or solution suggestion?
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;
this.remove = function(element){
if(!this.root){ //empty tree
return null;
}
if(!this.root.left && !this.root.right){ //delete root with no children
if(this.root.value === element){
this.root = null;
return;
}
else{
return null;
}
}
//find parent node of the element to delete
function findParent(node, previousNode, element){
if(node.value === element){
return previousNode;
}
if(element < node.value){
if(node.left){
return findParent(node.left, node, element);
}
else{
return null;
}
}
else{
if(node.right){
return findParent(node.right, node, element);
}
else{
return null;
}
}
}
let parentNode; //call findParent() on left or right child node of the root
if(element < this.root.value){
parentNode = findParent(this.root.left, this.root, element);
}
else{
parentNode = findParent(this.root.right, this.root, element);
}
if(!parentNode){ //element not found
return null;
}
//delete the element
if(element < parentNode.value){
parentNode.left = null;
}
else{
parentNode.right = null;
}
}
}
Challenge: Delete a Leaf Node in a Binary Search Tree
Link to the challenge: