Skip to main content

98.js

/** ------------------------------------------------------------------------------
*
* 98. Validate Binary Search Tree
* Topics: DFS, Binary Tree
* https://leetcode.com/problems/validate-binary-search-tree/?envType=problem-list-v2&envId=depth-first-search
*
------------------------------------------------------------------------------ */
/**
* 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) {
// const dfs = (node) => {
// if (!node.val) return true
// if (!node.left && !node.right) return true
// else if(node.right) {
// if (node.val >= node.right.val) return false
// } else {
// if (node.val <= node.left.val) return false
// }

// return dfs(node.left) && dfs(node.right)
// }

// return dfs(root)
// }

var isValidBST = function (root, min = -Infinity, max = Infinity) {
if (!root) return true
if (root.val <= min || root.val >= max) return false

return isValidBST(root.left, min, root.val) && isValidBST(root.right, root.val, max)
}

console.log(isValidBST(root))