Reputation: 5021
In my JavaScript code, I am trying to find a height of a given node in aBinary SearchTree.
Here is my code
class BinarySearchTree2 {
constructor() {
this.root = null;
}
findHeight(node = this.root,nodeData,level = 1) {
let root = node;
if(root === null)
return null;
if(root.data === nodeData)
return level;
let foundLevel = 0;
if(nodeData < root.data) {
foundLevel = findHeight(root.left,nodeData,level + 1);
}
// If you have found it on the left subtree, that's it, return
if(foundLevel !== 0)
return foundLevel;
foundLevel = findHeight(root.left,nodeData,level + 1);
return foundLevel;
}
}
Now, when I insert some nodes and try to find a height of a node like :
let BST = new BinarySearchTree2();
BST.insert(8);
BST.insert(3);
BST.insert(10);
BST.insert(1);
BST.insert(6);
BST.insert(14);
BST.insert(4);
BST.insert(7);
BST.insert(13);
BST.findHeight(this.root,14,1);
It throws error. Saying findHeight
is not defined.
What am I doing wrong?
Upvotes: 0
Views: 570
Reputation: 1349
If you want to call a method inside itself, you still need to use this
since the method you are trying to call is actually attached to the object itself. So,
class BinarySearchTree2 {
constructor() {
this.root = null;
}
findHeight(node = this.root,nodeData,level = 1) {
let root = node;
if(root === null)
return null;
if(root.data === nodeData)
return level;
let foundLevel = 0;
if(nodeData < root.data) {
// change here
foundLevel = this.findHeight(root.left,nodeData,level + 1);
}
// If you have found it on the left subtree, that's it, return
if(foundLevel !== 0)
return foundLevel;
// change here
foundLevel = this.findHeight(root.left,nodeData,level + 1);
return foundLevel;
}
}
would work as expected
Upvotes: 1
Reputation: 1896
This line should be
findHeight(node = this.root,nodeData,level = 1) {
Like this
findHeight = (node = this.root,nodeData,level = 1) => {
Or you need to bind your function to the clas in the constructor.
Upvotes: 0