I am trying to remove a root node in a binary search tree.
bst.remove(1) gives the correct output but it doesn't change the tree itself.
So if I check bst after calling bst.remove(1) the output is different. Why is it the case?
If I run bst=bst.left||bst.right;, I get the correct output, which leads me to believe that my function isn't changing the original tree in place.
remove(key) {
return this.removeImpl(key, this);
}
removeImpl(key, node){
if (node != null) {
if (key < node.value) {
// Key might be in the left subtree.
node.left = this.removeImpl(key, node.left);
} else if (key > node.value) {
node.right = this.removeImpl(key, node.right);
} else {
// Node found.
// Let's see if it has two children.
if (node.left && node.right) {
// Replace current node with
// predecessor data
node.value = this.minimum(node.right);
node.right = this.removeImpl(node.value, node.right);
} else {
// Only 1 child.
// Let's return the child that's valid.
node = node.left || node.right; //node to be removed becomes it's right or left child
}
}
}
return node;
}
var bst=new BST(1);
bst.insert(2);
bst.insert(3);
bst.insert(4);
bst.remove(1);