-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarysearchtree.py
More file actions
51 lines (43 loc) · 1.14 KB
/
binarysearchtree.py
File metadata and controls
51 lines (43 loc) · 1.14 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
50
51
# BinarySearchTree implementation
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BST(object):
def __init__(self, root):
self.root = Node(root)
def insert(self, new_val):
if self.root:
current = self.root
while current:
if new_val > current.value:
current = current.right
else:
current = current.left
else:
self.root = Node(new_val)
def search(self, find_val):
current = self.root
while current:
if find_val > current.value:
current = current.right
elif find_val < current.value:
current = current.left
else:
break
if current and current.value == find_val:
return True
return False
# Set up tree
tree = BST(4)
# Insert elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
# Check search
# Output should be True
print(tree.search(4))
# Output should be False
print(tree.search(6))