簡體   English   中英

JavaScript Class 解決方案,用於驗證二叉搜索樹

[英]JavaScript Class solution for Validate Binary Search Tree

我正在嘗試在 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 強制我運行 function 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;
};

我知道使用類有點矯枉過正,但我正在嘗試在任何我可以練習我的 OOP 的地方使用帶有 Javascript 的類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM