mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
Update 0098.验证二叉搜索树.md
将上一版本的代码改成跟题解思路相同.
This commit is contained in:
@ -372,18 +372,30 @@ class Solution:
|
|||||||
return res
|
return res
|
||||||
```
|
```
|
||||||
|
|
||||||
**递归** -
|
**递归** - 标准做法
|
||||||
|
|
||||||
```python
|
```python
|
||||||
class Solution:
|
class Solution:
|
||||||
def isValidBST(self, root: TreeNode) -> bool:
|
def isValidBST(self, root: TreeNode) -> bool:
|
||||||
def isBST(root, min_val, max_val):
|
# 规律: BST的中序遍历节点数值是从小到大.
|
||||||
if not root: return True
|
cur_max = -float("INF")
|
||||||
if root.val >= max_val or root.val <= min_val:
|
def __isValidBST(root: TreeNode) -> bool:
|
||||||
return False
|
nonlocal cur_max
|
||||||
return isBST(root.left, min_val, root.val) and isBST(root.right, root.val, max_val)
|
|
||||||
return isBST(root, float("-inf"), float("inf"))
|
|
||||||
|
|
||||||
|
if not root:
|
||||||
|
return True
|
||||||
|
|
||||||
|
is_left_valid = __isValidBST(root.left)
|
||||||
|
if cur_max < root.val:
|
||||||
|
cur_max = root.val
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
is_right_valid = __isValidBST(root.right)
|
||||||
|
|
||||||
|
return is_left_valid and is_right_valid
|
||||||
|
return __isValidBST(root)
|
||||||
|
```
|
||||||
|
```
|
||||||
# 迭代-中序遍历
|
# 迭代-中序遍历
|
||||||
class Solution:
|
class Solution:
|
||||||
def isValidBST(self, root: TreeNode) -> bool:
|
def isValidBST(self, root: TreeNode) -> bool:
|
||||||
|
Reference in New Issue
Block a user