-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary_search_tree.py
More file actions
49 lines (44 loc) · 1.41 KB
/
binary_search_tree.py
File metadata and controls
49 lines (44 loc) · 1.41 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
49
class Node():
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinarySearchTree():
def __init__(self):
self.root = None
def insert(self, value):
new_node = Node(value)
if self.root is None:
self.root = new_node
return True
else:
temp = self.root
while True:
if new_node.value == temp.value:
return False
elif new_node.value < temp.value:
if temp.left is not None:
temp = temp.left
else:
temp.left = new_node
return True
elif new_node.value > temp.value:
if temp.right is not None:
temp = temp.right
else:
temp.right = new_node
return True
def contains(self, value):
if self.root is None:
return False
else:
temp = self.root
while temp is not None:
if value < temp.value:
temp = temp.left
elif value > temp.value:
temp = temp.right
else:
return True
return False #it means that value doesn't exist
t1 = BinarySearchTree()