题解
第一种做法,递归左右子树
第二种做法中序遍历,然后遍历一遍slice即可,有一个坑就是value相同也是false
代码
func isValidBST(root *TreeNode) bool { return helper(root, math.MinInt64, math.MaxInt64) } func helper(root *TreeNode, lower, upper int) bool { if root == nil { return true } if root.Val <= lower || root.Val >= upper { return false } return helper(root.Left, lower, root.Val) && helper(root.Right, root.Val, upper) }
package main func main() { } type TreeNode struct { Val int Left *TreeNode Right *TreeNode } func isValidBST(root *TreeNode) bool { result := make([]int, 0) inorder(root, &result) return check(result) } func inorder(root *TreeNode, result *[]int) { if root == nil { return } inorder(root.Left, result) *result = append(*result, root.Val) inorder(root.Right, result) } func check(cnt []int) bool { for i := 0; i < len(cnt)-1; i++ { if cnt[i] >= cnt[i+1] { return false } } return true }