From b825b5a7c82023ee2ac1b2adc68cf75abc2ecd13 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Tue, 27 Dec 2022 00:30:43 -0500 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 | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 95ae783f..93c2272c 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -392,7 +392,26 @@ class Solution: return is_left_valid and is_right_valid return __isValidBST(root) ``` - +**递归** - 避免初始化最小值做法: +```python +class Solution: + def isValidBST(self, root: TreeNode) -> bool: + # 规律: BST的中序遍历节点数值是从小到大. + pre = None + def __isValidBST(root: TreeNode) -> bool: + nonlocal pre + + if not root: + return True + + is_left_valid = __isValidBST(root.left) + if pre and pre.val>=root.val: return False + pre = root + is_right_valid = __isValidBST(root.right) + + return is_left_valid and is_right_valid + return __isValidBST(root) +``` ```python 迭代-中序遍历 class Solution: