Merge pull request #479 from Miraclelucy/master

Update 0098.验证二叉搜索树.md - 增加了python3版本的简单递归法和迭代解法
This commit is contained in:
程序员Carl
2021-07-12 09:43:11 +08:00
committed by GitHub
2 changed files with 50 additions and 1 deletions

View File

@ -343,7 +343,7 @@ Python
# self.val = val
# self.left = left
# self.right = right
//递归法
# 递归法
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
res = [] //把二叉搜索树按中序遍历写成list
@ -355,6 +355,35 @@ class Solution:
return res
buildalist(root)
return res == sorted(res) and len(set(res)) == len(res) //检查list里的数有没有重复元素以及是否按从小到大排列
# 简单递归法
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def isBST(root, min_val, max_val):
if not root: return True
if root.val >= max_val or root.val <= min_val:
return False
return isBST(root.left, min_val, root.val) and isBST(root.right, root.val, max_val)
return isBST(root, float("-inf"), float("inf"))
# 迭代-中序遍历
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
stack = []
cur = root
pre = None
while cur or stack:
if cur: # 指针来访问节点,访问到最底层
stack.append(cur)
cur = cur.left
else: # 逐一处理节点
cur = stack.pop()
if pre and cur.val <= pre.val: # 比较当前节点和前节点的值的大小
return False
pre = cur
cur = cur.right
return True
```
Go
```Go

View File

@ -222,6 +222,26 @@ class Solution:
for i in range(len(res)-1): // 统计有序数组的最小差值
r = min(abs(res[i]-res[i+1]),r)
return r
# 迭代法-中序遍历
class Solution:
def getMinimumDifference(self, root: TreeNode) -> int:
stack = []
cur = root
pre = None
result = float('inf')
while cur or stack:
if cur: # 指针来访问节点,访问到最底层
stack.append(cur)
cur = cur.left
else: # 逐一处理节点
cur = stack.pop()
if pre: # 当前节点和前节点的值的差值
result = min(result, cur.val - pre.val)
pre = cur
cur = cur.right
return result
```
Go
> 中序遍历,然后计算最小差值