mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Update 0098.验证二叉搜索树.md
更改递归部分代码 1. 更新上一版代码格式 使其更符合PEP8. 2. 把代码细节都暴露出来, 逻辑更加清晰.
This commit is contained in:
@ -337,6 +337,8 @@ class Solution {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
|
||||||
|
**递归** - 利用BST中序遍历特性
|
||||||
```python
|
```python
|
||||||
# Definition for a binary tree node.
|
# Definition for a binary tree node.
|
||||||
# class TreeNode:
|
# class TreeNode:
|
||||||
@ -344,18 +346,30 @@ Python:
|
|||||||
# self.val = val
|
# self.val = val
|
||||||
# self.left = left
|
# self.left = left
|
||||||
# self.right = right
|
# self.right = right
|
||||||
# 递归法
|
|
||||||
class Solution:
|
class Solution:
|
||||||
def isValidBST(self, root: TreeNode) -> bool:
|
def isValidBST(self, root: TreeNode) -> bool:
|
||||||
res = [] //把二叉搜索树按中序遍历写成list
|
# 思路: 利用BST中序遍历的特性.
|
||||||
def buildalist(root):
|
# 中序遍历输出的二叉搜索树节点的数值是有序序列
|
||||||
if not root: return
|
candidate_list = []
|
||||||
buildalist(root.left) //左
|
|
||||||
res.append(root.val) //中
|
def __traverse(root: TreeNode) -> None:
|
||||||
buildalist(root.right) //右
|
nonlocal candidate_list
|
||||||
return res
|
if not root:
|
||||||
buildalist(root)
|
return
|
||||||
return res == sorted(res) and len(set(res)) == len(res) //检查list里的数有没有重复元素,以及是否按从小到大排列
|
__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:
|
class Solution:
|
||||||
|
Reference in New Issue
Block a user