Merge pull request #550 from KelvinG-611/98. Validate-Binary-Search-Tree

98. validate binary search tree
This commit is contained in:
程序员Carl
2021-08-03 09:51:30 +08:00
committed by GitHub

View File

@ -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,29 +346,56 @@ 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]: # ⚠️ 注意: Leetcode定义二叉搜索树中不能有重复元素
return False
return True
__traverse(root)
res = __is_sorted(candidate_list)
return res
```
# 简单递归 **递归** - 标准做
```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:
nonlocal cur_max
if not root:
return True
is_left_valid = __isValidBST(root.left)
if cur_max < root.val:
cur_max = root.val
else:
return False return False
return isBST(root.left, min_val, root.val) and isBST(root.right, root.val, max_val) is_right_valid = __isValidBST(root.right)
return isBST(root, float("-inf"), float("inf"))
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: