zentan66 / daily-coding

日常手写算法,编程题
0 stars 0 forks source link

LeetCode-验证二叉搜索树 #19

Open zentan66 opened 3 years ago

zentan66 commented 3 years ago

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

节点的左子树只包含小于当前节点的数。 节点的右子树只包含大于当前节点的数。 所有左子树和右子树自身必须也是二叉搜索树。

难度:⭐️⭐️

zentan66 commented 3 years ago

编码

var isValidBST = function (root) {
  function helper(root, lower, upper) {
    if (root === null) {
      return true
    }
    if (root.val <= lower || root.val >= upper) {
      return false
    }
    return (
      helper(root.left, lower, root.val) && helper(root.right, root.val, upper)
    )
  }
  return helper(root, -Infinity, Infinity)
}