-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst.py
81 lines (66 loc) · 2.08 KB
/
bst.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
81
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def __str__(self):
return str(self.value)
class BinarySearchTree:
def __init__(self):
self.root = None
def create(self, value):
if self.root is None:
self.root = Node(value)
else:
curr = self.root
while True:
if value < curr.value:
if curr.left is None:
curr.left = Node(value)
break
else:
curr = curr.left
else:
if curr.right is None:
curr.right = Node(value)
break
else:
curr = curr.right
def search(self, value):
if self.root is None:
return None
else:
curr = self.root
while True:
if value == curr.value:
return curr
else:
if value < curr.value:
if curr.left is None:
return None
else:
curr = curr.left
else:
if curr.right is None:
return None
else:
curr = curr.right
def checkBST(self):
visited = []
queue = []
queue.append(self.root)
while len(queue) > 0:
curr = queue.pop()
# print(curr.value)
if curr in visited:
return False
if not curr.left is None:
if curr.value < curr.left.value:
return False
queue.append(curr.left)
if not curr.right is None:
if curr.value > curr.right.value:
return False
queue.append(curr.right)
visited.append(curr)
return True