Merge pull request #929 from iiiuwioajdks/master

FIX: 更正0098.验证二叉搜索树go语言版的代码
This commit is contained in:
程序员Carl
2021-12-07 10:07:40 +08:00
committed by GitHub

View File

@ -414,19 +414,24 @@ class Solution:
import "math"
func isValidBST(root *TreeNode) bool {
if root == nil {
return true
}
return isBST(root, math.MinInt64, math.MaxFloat64)
// 二叉搜索树也可以是空树
if root == nil {
return true
}
// 由题目中的数据限制可以得出min和max
return check(root,math.MinInt64,math.MaxInt64)
}
func isBST(root *TreeNode, min, max int) bool {
if root == nil {
return true
}
if min >= root.Val || max <= root.Val {
return false
}
return isBST(root.Left, min, root.Val) && isBST(root.Right, root.Val, max)
func check(node *TreeNode,min,max int64) bool {
if node == nil {
return true
}
if min >= int64(node.Val) || max <= int64(node.Val) {
return false
}
// 分别对左子树和右子树递归判断如果左子树和右子树都符合则返回true
return check(node.Right,int64(node.Val),max) && check(node.Left,min,int64(node.Val))
}
```
```go