98.validate-binary-search-tree
Last updated
Last updated
5
/ \
1 4
/ \ / \
null null 3 6
Input: root = [5, 1, 4, null, null, 3, 6]
Output: false
// 因為 4 的節點值必須比根節點 5 大 5
/ \
4 6
/ \ / \
null null 3 7/**
* 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, max = null, min = null) {
if (!root) return true
if (max && root.val >= max.val) return false
if (min && root.val <= min.val) return false
return isValidBST(root.left, root, min) && isValidBST(root.right, max, root);
};