-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathvalid_bst_st.py
80 lines (63 loc) · 1.69 KB
/
valid_bst_st.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
71
72
73
74
75
76
77
78
79
80
import os, sys
currentdir = os.path.dirname(os.path.realpath(__file__))
parentdir = os.path.dirname(currentdir)
sys.path.append(parentdir)
from collections import deque
import collections
from typing import List
from binarytree import BinaryTree, Node
tests = {
1: [5,1,4,'N','N',3,6],
2: [2,1,3],
3: [8,6,15,3,7,12,21],
4: [1, 1],
5: [8,5,15,6,7,12,21]
}
res = {
1: False,
2: True,
3: True,
4: False,
5: False
}
def parse_tree(tree_input):
bst = BinaryTree()
if not tree_input:
return bst
input_datas = []
for item in tree_input:
if item == 'N':
input_datas.append(None)
else:
input_datas.append(int(item))
bst.create_bst(input_datas)
return bst
def check_result(index: int, output: int):
if index > len(tests):
raise RuntimeError(f'Failed to get {index}th case')
return res.get(index, False) == output
def isValidBST(root: Node) -> bool:
if root == None:
return True
stack = []
stack.append((root, float('-inf'), float('inf')))
while stack:
node, low, high = stack.pop()
data = node.data
if data <= low or data >= high:
return False
if node.left:
stack.append((node.left, low, data))
if node.right:
stack.append((node.right, data, high))
return True
def main():
for index, tree_input in tests.items():
bst = parse_tree(tree_input)
res = isValidBST(bst.root)
if check_result(index, res):
print(f'Test case {index} is correct: {res}')
else:
print(f'Test case {index} is failed: {res}')
if __name__ == '__main__':
main()