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.

  **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:

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;
  this.add=function(value){
    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()
tree.add(10)
tree.add(5)
tree.add(15)
tree.add(3)
tree.add(7)
displayTree(tree)
tree.remove(tree.root, 7)
displayTree(tree)

yep :grinning: I solved it somehow iteratively… now that understand the issue more I could play with recursive solution

1 Like

thanks for help :pray: ! I will play around with it

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.