harrytothemoon / leetcodeAplus

Leetcode meeting note
2 stars 0 forks source link

[98] Validate Binary Search Tree #69

Open tsungtingdu opened 3 years ago

tsungtingdu commented 3 years ago
var isValidBST = function(root) {
    if (root === null || root.val === null) return []
    let ans = true
    traverseInOrder(root, []) 
    return ans

    function traverseInOrder(node, list) {
        if (node.left) {
            traverseInOrder(node.left, list)
        }
        let last = list[list.length - 1]
        if ((last || last === 0) && last >= node.val) {
            ans = false
            return 
        } else {
            list.push(node.val)
        }

        if (node.right) {
            traverseInOrder(node.right, list)
        }
    }
};
henry22 commented 3 years ago
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isValidBST = function(root, min = null, max = null) {
    if(root === null) return true;

    if(max !== null && root.val >= max) {
        return false;
    }

    if(min !== null && root.val <= min) {
        return false;
    }

    if(root.left && !isValidBST(root.left, min, root.val)) {
        return false;
    }

    if(root.right && !isValidBST(root.right, root.val, max)) {
        return false;
    }

    return true;
};
harrytothemoon commented 3 years ago
var isValidBST = function(root) {
    let prev = null
    let valid = true
    // inorder
    const traverse = (node) => {
        if (!node || !valid) return
        traverse(node.left)
        if (prev !== null && node.val <= prev) {
            valid = false
        }
        prev = node.val
        traverse(node.right)
    }
    traverse(root)
    return valid
};