package main
import (
"fmt"
"math"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func isValidBST(root *TreeNode) bool {
return validate(root, math.Inf(-1), math.Inf(1))
}
func validate(node *TreeNode, min, max float64) bool {
if node == nil {
return true
}
val := float64(node.Val)
if val <= min || val >= max {
return false
}
// Check left subtree with updated max
if !validate(node.Left, min, val) {
return false
}
// Check right subtree with updated min
if !validate(node.Right, val, max) {
return false
}
return true
}
func main() {
root := &TreeNode{Val: 5}
root.Left = &TreeNode{Val: 3}
root.Right = &TreeNode{Val: 7}
root.Left.Left = &TreeNode{Val: 2}
root.Left.Right = &TreeNode{Val: 4}
root.Right.Right = &TreeNode{Val: 8}
fmt.Println(isValidBST(root))
}return validate(root, math.Inf(-1), math.Inf(1))
start validation with infinite range for root
if node == nil {
return true
}
empty node is valid BST by definition
if val <= min || val >= max {
return false
}
check if current node violates min/max range
if !validate(node.Left, min, val) {
return false
}
validate left subtree with updated max limit
if !validate(node.Right, val, max) {
return false
}
validate right subtree with updated min limit