39 lines
669 B
Go
39 lines
669 B
Go
package q98
|
|
|
|
type TreeNode struct {
|
|
Val int
|
|
Left *TreeNode
|
|
Right *TreeNode
|
|
}
|
|
|
|
func isValid(node *TreeNode) (bool, int, int) {
|
|
if node.Left == nil && node.Right == nil {
|
|
return true, node.Val, node.Val
|
|
}
|
|
|
|
minv, maxv := node.Val, node.Val
|
|
|
|
if node.Left != nil {
|
|
valid, lmin, lmax := isValid(node.Left)
|
|
if !valid || lmax >= node.Val {
|
|
return false, 0, 0
|
|
}
|
|
minv = lmin
|
|
}
|
|
if node.Right != nil {
|
|
valid, rmin, rmax := isValid(node.Right)
|
|
if !valid || rmin <= node.Val {
|
|
return false, 0, 0
|
|
}
|
|
maxv = rmax
|
|
}
|
|
|
|
return true, minv, maxv
|
|
}
|
|
|
|
func isValidBST(root *TreeNode) bool {
|
|
valid, _, _ := isValid(root)
|
|
return valid
|
|
}
|
|
|
|
var _ = isValidBST
|