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.
**Your code so far**
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
Link to the challenge: