Reputation: 594
I am trying to use the find() method for BST. However, I am encountering errors when I place the 'if' statement incorrectly. When I swap the following 2 lines, my code gave me an error TypeError: Cannot read properties of null (reading 'val')
. However, if I used a "else if" for the second statement, it works. Not sure why.
if (val > current.val) current = current.right // these 2 lines were swapped which gave an error
if (val < current.val) current = current.left // these 2 lines were swapped which gave an error
Below is the full code.
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
class BST {
constructor() {
this.root = null;
}
insert(val) {
let newNode = new Node(val)
if (!this.root) {
this.root = newNode
return this;
}
let current = this.root
while (true) {
if (val === current.val) return undefined
if (val < current.val) {
if (current.left === null) {
current.left = newNode
return this;
} else {
current = current.left
}
}
if (val > current.val) {
if (current.right === null) {
current.right = newNode
return this;
} else {
current = current.right
}
}
}
}
find(val) {
if (!this.root) return false
let current = this.root
while (current) {
if (val === current.val) return true
console.log(current.val)
if (val > current.val) current = current.right // these 2 lines were swapped
if (val < current.val) current = current.left // these 2 lines were swapped
}
return false
}
}
let tree = new BST();
console.log(tree.insert(10));
console.log(tree.insert(5));
console.log(tree.insert(13));
console.log(tree.insert(11));
console.log(tree.insert(2));
console.log(tree.insert(16));
console.log(tree.insert(7));
console.log(tree.find(333))
Upvotes: 0
Views: 257
Reputation: 489
Because you ask on your second "if" about the current.val but on the first "if" you change the current to null (when you got to the end of the tree), this is why you should use "else if" or to ask if the current == null before you ask about it again.
Notice that if you swap between the lines it won't solve the problem, just transfer the exception to the cases when you have an item that is smaller than any other element in the tree.
Upvotes: 2