From 3ae922f6f17a3d7ccc9a6f713572a4a96bfba4e5 Mon Sep 17 00:00:00 2001 From: mx lai <1721261216@qq.com> Date: Sun, 5 Dec 2021 19:56:17 +0800 Subject: [PATCH] =?UTF-8?q?FIX:=20=E6=9B=B4=E6=AD=A30098.=E9=AA=8C?= =?UTF-8?q?=E8=AF=81=E4=BA=8C=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91go?= =?UTF-8?q?=E8=AF=AD=E8=A8=80=E7=89=88=E7=9A=84=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0098.验证二叉搜索树.md | 29 +++++++++++++++----------- 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index ec265615..82d1941e 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -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