描述
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
- 节点的左子树只包含小于当前节点的数。(右子树的所有节点都要大于根节点)
- 节点的右子树只包含大于当前节点的数。(左子树的所有节点都要小于根节点)
- 所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 1:
输入: 5 / \ 1 4 / \ 3 6 输出: false 解释: 输入为: [5,1,4,null,null,3,6]。 根节点的值为 5 ,但是其右子节点值为 4 。
题解
这道题的具体解法,参考力扣官方题解的方法一
/*** 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) {return helper(root, Infinity, -Infinity)};const helper = (root, upper, lower) => {if (!root) return trueif (root.val <= lower || root.val >= upper) return falsereturn helper(root.left, root.val, lower) && helper(root.right, upper, root.val)}
