-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path98_validate_binary_search_tree
More file actions
40 lines (34 loc) · 1.37 KB
/
98_validate_binary_search_tree
File metadata and controls
40 lines (34 loc) · 1.37 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
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
def isBSTHelper(node, lower_limit, upper_limit):
if lower_limit is not None and node.val <= lower_limit:
return False
if upper_limit is not None and upper_limit <= node.val:
return False
left = isBSTHelper(node.left, lower_limit, node.val) if node.left else True
if left:
right = isBSTHelper(node.right, node.val, upper_limit) if node.right else True
return right
else:
return False
return isBSTHelper(root, None, None)
class Solution(object):
def isValidBST(self, root, lessThan = float('inf'), largerThan = float('-inf')):
if not root:
return True
if root.val <= largerThan or root.val >= lessThan:
return False
return self.isValidBST(root.left, min(lessThan, root.val), largerThan) and \
self.isValidBST(root.right, lessThan, max(root.val, largerThan))