I have a generic binary search tree that uses a comparator function to evaluate which value is bigger. This is my remove method:
remove(data) {
const removeHelper = (node, data) => {
if (!node) return null;
if (this.#comparator(data, node.data) === 0) {
if (!node.left && !node.right) return null;
if (!node.left) return node.right;
if (!node.right) return node.left;
let tmp = node.right;
while (!tmp.left) {
tmp = tmp.left;
}
node.data = tmp.data;
node.right = removeHelper(node.right, tmp.data);
} else if (this.#comparator(data, node.data) === -1) {
node.left = removeHelper(node.left, data);
return node;
} else {
node.right = removeHelper(node.right, data);
return node;
}
};
this.root = removeHelper(this.root, data);
return data;
}
I keep getting the error: TypeError: Cannot read properties of null (reading 'left')
reffering to this line: (while (!tmp.left) )
How is my remove method not supposed to read property types of null if thats what the entire method functions off of