Skip to content

Commit 1250c16

Browse files
Merge pull request youngyangyang04#550 from KelvinG-611/98. Validate-Binary-Search-Tree
98. validate binary search tree
2 parents 90e4adc + 0fdede8 commit 1250c16

File tree

1 file changed

+47
-18
lines changed

1 file changed

+47
-18
lines changed

problems/0098.验证二叉搜索树.md

Lines changed: 47 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -337,36 +337,65 @@ class Solution {
337337
```
338338

339339
Python:
340+
341+
**递归** - 利用BST中序遍历特性,把树"压缩"成数组
340342
```python
341343
# Definition for a binary tree node.
342344
# class TreeNode:
343345
# def __init__(self, val=0, left=None, right=None):
344346
# self.val = val
345347
# self.left = left
346348
# self.right = right
347-
# 递归法
348349
class Solution:
349350
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
361378
class Solution:
362379
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:
366392
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+
```
370399
# 迭代-中序遍历
371400
class Solution:
372401
def isValidBST(self, root: TreeNode) -> bool:

0 commit comments

Comments
 (0)