@@ -337,36 +337,65 @@ class Solution {
337
337
```
338
338
339
339
Python:
340
+
341
+ ** 递归** - 利用BST中序遍历特性,把树"压缩"成数组
340
342
``` python
341
343
# Definition for a binary tree node.
342
344
# class TreeNode:
343
345
# def __init__(self, val=0, left=None, right=None):
344
346
# self.val = val
345
347
# self.left = left
346
348
# self.right = right
347
- # 递归法
348
349
class Solution :
349
350
def isValidBST (self , root : TreeNode) -> bool :
350
- res = [] // 把二叉搜索树按中序遍历写成list
351
- def buildalist (root ):
352
- if not root: return
353
- buildalist(root.left) // 左
354
- res.append(root.val) // 中
355
- buildalist(root.right) // 右
356
- return res
357
- buildalist(root)
358
- return res == sorted (res) and len (set (res)) == len (res) // 检查list 里的数有没有重复元素,以及是否按从小到大排列
359
-
360
- # 简单递归法
351
+ # 思路: 利用BST中序遍历的特性.
352
+ # 中序遍历输出的二叉搜索树节点的数值是有序序列
353
+ candidate_list = []
354
+
355
+ def __traverse (root : TreeNode) -> None :
356
+ nonlocal candidate_list
357
+ if not root:
358
+ return
359
+ __traverse(root.left)
360
+ candidate_list.append(root.val)
361
+ __traverse(root.right)
362
+
363
+ def __is_sorted (nums : list ) -> bool :
364
+ for i in range (1 , len (nums)):
365
+ if nums[i] <= nums[i - 1 ]: # ⚠️ 注意: Leetcode定义二叉搜索树中不能有重复元素
366
+ return False
367
+ return True
368
+
369
+ __traverse(root)
370
+ res = __is_sorted(candidate_list)
371
+
372
+ return res
373
+ ```
374
+
375
+ ** 递归** - 标准做法
376
+
377
+ ``` python
361
378
class Solution :
362
379
def isValidBST (self , root : TreeNode) -> bool :
363
- def isBST (root , min_val , max_val ):
364
- if not root: return True
365
- if root.val >= max_val or root.val <= min_val:
380
+ # 规律: BST的中序遍历节点数值是从小到大.
381
+ cur_max = - float (" INF" )
382
+ def __isValidBST (root : TreeNode) -> bool :
383
+ nonlocal cur_max
384
+
385
+ if not root:
386
+ return True
387
+
388
+ is_left_valid = __isValidBST(root.left)
389
+ if cur_max < root.val:
390
+ cur_max = root.val
391
+ else :
366
392
return False
367
- return isBST(root.left, min_val, root.val) and isBST(root.right, root.val, max_val)
368
- return isBST(root, float (" -inf" ), float (" inf" ))
369
-
393
+ is_right_valid = __isValidBST(root.right)
394
+
395
+ return is_left_valid and is_right_valid
396
+ return __isValidBST(root)
397
+ ```
398
+ ```
370
399
# 迭代-中序遍历
371
400
class Solution:
372
401
def isValidBST(self, root: TreeNode) -> bool:
0 commit comments