forked from ngiengkianyew/daily-coding-problem
-
Notifications
You must be signed in to change notification settings - Fork 0
/
problem_089.py
70 lines (51 loc) · 1022 Bytes
/
problem_089.py
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import sys
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def is_valid_bst_node_helper(node, lb, ub):
if node and node.val <= ub and node.val >= lb:
return is_valid_bst_node_helper(node.left, lb, node.val) and \
is_valid_bst_node_helper(node.right, node.val, ub)
return not node # if node is None, it's a valid BST
def is_valid_bst(root):
return is_valid_bst_node_helper(root, -sys.maxsize, sys.maxsize)
# Tests
assert is_valid_bst(None)
a = Node(3)
b = Node(2)
c = Node(6)
d = Node(1)
e = Node(3)
f = Node(4)
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
assert is_valid_bst(a)
a = Node(1)
b = Node(2)
c = Node(6)
d = Node(1)
e = Node(3)
f = Node(4)
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
assert not is_valid_bst(a)
a = Node(3)
b = Node(2)
c = Node(6)
d = Node(1)
e = Node(4)
f = Node(4)
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
assert not is_valid_bst(a)