用于验证二进制搜索树的JavaScript类解决方案



我正在尝试在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);

感谢大家的回答。现在我理解了这个问题: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;
};

我知道使用Classes有点过头了,但我正在尽可能地将Classes与Javascript一起使用,以练习OOP。

最新更新