98. 验证二叉搜索树

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */

type Check struct {
    last int
    flag bool
}
// 中序遍历
func (c *Check) isValidBST(root *TreeNode) bool {
     if root == nil {
        return true
    }

    if c.flag && root.Left != nil {
        c.isValidBST(root.Left)
    }
    if root.Val <= c.last {
        c.flag = false 
    }
    c.last = root.Val 
    if c.flag && root.Right != nil {
        c.isValidBST(root.Right)
    }
    return c.flag 
}
func isValidBST(root *TreeNode) bool {
   c := &Check{
       last: math.MinInt64,
    flag: true,
    }
    return c.isValidBST(root)
}

Last updated

Was this helpful?