From 0fdede8c944b5052160370b3fe1241810021cfa3 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Sun, 1 Aug 2021 22:53:23 -0400 Subject: [PATCH] =?UTF-8?q?Update=200098.=E9=AA=8C=E8=AF=81=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=90=9C=E7=B4=A2=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将上一版本的代码改成跟题解思路相同. --- problems/0098.验证二叉搜索树.md | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index cf8651f3..a7634849 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -372,18 +372,30 @@ class Solution: return res ``` -**递归** - +**递归** - 标准做法 ```python class Solution: def isValidBST(self, root: TreeNode) -> bool: - def isBST(root, min_val, max_val): - if not root: return True - if root.val >= max_val or root.val <= min_val: + # 规律: BST的中序遍历节点数值是从小到大. + cur_max = -float("INF") + def __isValidBST(root: TreeNode) -> bool: + nonlocal cur_max + + if not root: + return True + + is_left_valid = __isValidBST(root.left) + if cur_max < root.val: + cur_max = root.val + else: return False - return isBST(root.left, min_val, root.val) and isBST(root.right, root.val, max_val) - return isBST(root, float("-inf"), float("inf")) - + is_right_valid = __isValidBST(root.right) + + return is_left_valid and is_right_valid + return __isValidBST(root) +``` +``` # 迭代-中序遍历 class Solution: def isValidBST(self, root: TreeNode) -> bool: