Here is my constructor function as well as my 'add' method...
function BinarySearchTree(value) {
this.value = value;
this.right = null;
this.left = null;
}
BinarySearchTree.prototype.add = function(value) {
if (value < this.value) {
if (this.left) this.left.add(value);
else this.left = new BinarySearchTree(value);
}
if (value > this.value) {
if (this.right) this.right.add(value);
else this.right = new BinarySearchTree(value);
}
};
Here is the 'getNodeHeight' method I am trying to make...
BinarySearchTree.prototype.getNodeHeight = function(node) {
if (node.value === null) {
return -1;
}
return Math.max(this.getNodeHeight(node.left), this.getNodeHeight(node.right)) 1;
}
And here are the test cases I am running...
binarySearchTree = new BinarySearchTree(5);
binarySearchTree.left = new BinarySearchTree(3);
binarySearchTree.left.left = new BinarySearchTree(1);
binarySearchTree.getNodeHeight(this);
Every time I log the last one to the console I get "Cannot read properties of undefined (reading 'value')". I believe I may be using the 'this' keyword incorrectly... but I've tried messing with it and can't figure it out!
Any tips, tricks, or help would be greatly appreciated... Thank you for your time!
CodePudding user response:
The problem is in the first line of your getNodeHeight
function when it's called on node.right
(which is null
). null
doesn't have a value
property. The same error will occur if you evaluate
null.value
Fix this by changing
if (node.value === null) ...
to
if (!node) ...
On further investigation, the use of the this
keyword in binarySearchTree.getNodeHeight(this)
is likely returning a reference to your Window object instead of the binarySearchTree
. Try calling the method by way of
BinarySearchTree.prototype.getNodeHeight(binarySearchTree)
Good luck!
CodePudding user response:
There are 2 issues, one that was pointed out by @Austin regarding the check on whether the input value is null.
The other issue is that there is no default value for getNodeHeight
. For this I'm assuming that you're expecting the default behavior to find the height of the whole tree. Passing in this
to getNodeHeight
is passing in the context where you are creating the BinarySearchTree - not the instance.
function BinarySearchTree(value) {
this.value = value;
this.right = null;
this.left = null;
}
BinarySearchTree.prototype.add = function(value) {
if (value < this.value) {
if (this.left) this.left.add(value);
else this.left = new BinarySearchTree(value);
}
if (value > this.value) {
if (this.right) this.right.add(value);
else this.right = new BinarySearchTree(value);
}
};
BinarySearchTree.prototype.getNodeHeight = function(node = this) {
if (node === null) {
return -1;
}
return Math.max(this.getNodeHeight(node.left), this.getNodeHeight(node.right)) 1;
}
const binarySearchTree = new BinarySearchTree(5);
binarySearchTree.left = new BinarySearchTree(3);
binarySearchTree.left.left = new BinarySearchTree(1);
console.log(binarySearchTree.getNodeHeight());