LeetCode98 验证二叉搜索树

45 阅读1分钟

leetcode.cn/problems/va… image.png

解法一: 基于分解子问题思维模式的递归

根据 BST 的定义,root 的整个左子树都要小于 root.val,整个右子树都要大于 root.val

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isValidBST(root *TreeNode) bool {
    // 如果对整数范围有更高要求,使用 math.MinInt64 和 math.MaxInt64 是一种更安全的做法
    return checker(root, math.MinInt64, math.MaxInt64)
}

func checker(root *TreeNode, min, max int) bool{
    if root == nil{
        return true
    }
    if root.Val <= min || root.Val >= max{
        return false
    }
    return checker(root.Left, min, root.Val) && checker(root.Right, root.Val, max)
}