# Data Structures - Delete a Leaf Node in a Binary Search Tree

Tell us what’s happening:
I have created this recursive function and want to solve this challenge recursively, iteratively would be more messy. What I am trying to do here is find the node in binary tree set it to null but I don’t know if the parent node of node will have left or right set to null. Also I am not sure if my code does what I think it does. Some variables I created for test purposes to know what’s going on.

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 = function(element) {
let node = this.root;
let found = false;
if(node === null) return null;
if(node.right === null && node.right === null) {
this.root = null;
}
console.log(element)
const recursion = ( node ) => {
console.log(node);
if(node === null) return null;

if( node.value === element ) {
node = null;
found = true;
return;
}

if(node !== null && node.value !== element) {
recursion(node.left);
}

if(node !== null && node.value !== element) {
recursion(node.right);
}

};

recursion(node);
console.log(found);
}
}

Challenge: Data Structures - Delete a Leaf Node in a Binary Search Tree

is there a typo here?

1 Like

i dunno but i would add code to see whats happening and play around:

function BinarySearchTree() {
this.root = null;
const newNode = new Node(value)
if(this.root === null) { this.root = newNode }
else{
this.insertNode(this.root, newNode)
}
}
this.insertNode=function(node, newNode) {
if(newNode.value < node.value){
if(!node.left){node.left = newNode}
else{
this.insertNode(node.left, newNode)
}
}else{
if(!node.right){node.right = newNode}
else{
this.insertNode(node.right, newNode)
}
}
}
// Only change code below this line

then at end do:

let tree=new BinarySearchTree()