Delete a Leaf Node in a Binary Search Tree

Tell us what’s happening:

This was supposed to be the easy one. Recursion hurts my brain. :frowning:

Can anyone explain why I’m failing this one? I checked beau’s video and this is exactly what he’s doing too as far as I can tell.

Failing:
If the root node has no children, deleting it sets the root to null .
The remove method removes leaf nodes from the tree

Thanks!

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;
    // case 1: target has no children, change code below this line
    this.remove = function (data){
        var removeNode = function (node, data) {
            if (node == null){
                return null;
            }
            if (node.data == data) {
                if (node.left==null && node.right == null){
                    return null
                }
            } else if (data < node.data) {
                node.left = removeNode(node.left, data);
                return node;
            } else {
                node.right = removeNode(node.right, data);
                return node;
            }
        }
        return removeNode(this.root, data);
    }
}

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0.

Link to the challenge:
https://learn.freecodecamp.org/coding-interview-prep/data-structures/delete-a-leaf-node-in-a-binary-search-tree

Hi there!

I looked at your code and everything is correct apart from two small details, look at the attributes that the node object has above in the code. You are using node.data but does node have data as an attribute?
Look at the video again at the remove part, you have defined a method but it is just returning things, have you set this.root to the new value? :slight_smile:

Binary search trees and recursion is a hard part, good job managing to get this down, hope this helped!

1 Like

Oh wow. That did it. Thank you!!!