我正在尝试在JavaScript中使用Class
来解决此问题:验证二进制搜索树。如果我使用函数,则可以正常工作,但是使用此代码,我总是会出错(使用LeetCode):
isValidBST is not a function
代码如下:
class Solution {
constructor(root) {
this.root = root;
}
get result() {
return this.helper(this.root, -Infinity, Infinity);
}
helper(root, low, high) {
if (!root) return true;
else {
let val = root.val;
if (val <= low || val >= high) return false;
if (!this.helper(root.right, val, high)) return false;
if (!this.helper(root.left, low, val)) return false;
return true;
}
}
}
var isValidBST = new Solution(root);
isValidBST.result();
我很困惑。我尝试过:
isValidBST.result();
isValidBST.result;
console.log(isValidBST.result);
答案 0 :(得分:0)
谢谢你们的回答。现在我了解了这个问题:LeetCode强制我运行带有参数isValidBST
的函数root
并返回结果。
这样做可以解决此问题:
class Solution {
constructor(root) {
this.root = root;
}
get result() {
return this.helper(this.root, -Infinity, Infinity);
}
helper(root, low, high) {
if (!root) return true;
else {
let val = root.val;
if (val <= low || val >= high) return false;
if (!this.helper(root.right, val, high)) return false;
if (!this.helper(root.left, low, val)) return false;
return true;
}
}
}
var isValidBST = function(root) {
const res = new Solution(root)
return res.result;
};
我知道使用类是一种矫kill过正的方法,但是我想在任何可以练习OOP的地方都使用Java类。