From b87d619cdd1ab886055d94cb4b878f550fe51ea7 Mon Sep 17 00:00:00 2001 From: Kelvin Date: Sun, 1 Aug 2021 13:54:51 -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 更改递归部分代码 1. 更新上一版代码格式 使其更符合PEP8. 2. 把代码细节都暴露出来, 逻辑更加清晰. --- problems/0098.验证二叉搜索树.md | 34 ++++++++++++++++++-------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/problems/0098.验证二叉搜索树.md b/problems/0098.验证二叉搜索树.md index 248d10f1..a271b977 100644 --- a/problems/0098.验证二叉搜索树.md +++ b/problems/0098.验证二叉搜索树.md @@ -337,6 +337,8 @@ class Solution { ``` Python: + +**递归** - 利用BST中序遍历特性 ```python # Definition for a binary tree node. # class TreeNode: @@ -344,18 +346,30 @@ Python: # self.val = val # self.left = left # self.right = right -# 递归法 class Solution: def isValidBST(self, root: TreeNode) -> bool: - res = [] //把二叉搜索树按中序遍历写成list - def buildalist(root): - if not root: return - buildalist(root.left) //左 - res.append(root.val) //中 - buildalist(root.right) //右 - return res - buildalist(root) - return res == sorted(res) and len(set(res)) == len(res) //检查list里的数有没有重复元素,以及是否按从小到大排列 + # 思路: 利用BST中序遍历的特性. + # 中序遍历输出的二叉搜索树节点的数值是有序序列 + candidate_list = [] + + def __traverse(root: TreeNode) -> None: + nonlocal candidate_list + if not root: + return + __traverse(root.left) + candidate_list.append(root.val) + __traverse(root.right) + + def __is_sorted(nums: list) -> bool: + for i in range(1, len(nums)): + if nums[i] <= nums[i - 1]: + return False + return True + + __traverse(root) + res = __is_sorted(candidate_list) + + return res # 简单递归法 class Solution: