-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathvalid_bst.py
More file actions
48 lines (39 loc) · 1.33 KB
/
valid_bst.py
File metadata and controls
48 lines (39 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# 验证二叉搜索树
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.prev = None
# 中序遍历,然后看数据是否完全有序
def isValidBST_1(self, root: TreeNode) -> bool:
def inOrder(node: TreeNode):
if not node:
return
inOrder(node.left)
res.append(node.val)
inOrder(node.right)
res = []
inOrder(root)
return sorted(set(res)) == res
# 中序遍历,无需保存全部的数据,前后数据比较即可
def isValidBST_2(self, root: TreeNode) -> bool:
if not root:
return True
if not self.isValidBST_2(root.left):
return False
if self.prev and self.prev.val >= root.val:
return False
self.prev = root
return self.isValidBST_2(root.right)
# 递归的方式
def isValidBST_3(self, root: TreeNode) -> bool:
def helper(node: TreeNode, mi, ma):
if not node:
return True
if node.val >= ma or node.val <= mi:
return False
return helper(node.left, mi, node.val) and helper(node.right, node.val, ma)
return helper(root, float('-inf'), float('inf'))