-
Notifications
You must be signed in to change notification settings - Fork 0
/
bst.py
67 lines (50 loc) · 1.31 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
# Binary Search Tree
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):
"""Inserts a new value into the tree"""
curr = self.root
parent = None
if self.root is None:
return Node(new_val)
while curr:
parent = curr
if new_val < curr.value:
curr = curr.left
else:
curr = curr.right
if new_val < parent.value:
parent.left = Node(new_val)
else:
parent.right = Node(new_val)
return self.root
def search(self, find_val):
"""Searches for a value in the tree
Returns True if in tree, False otherwise"""
curr = self.root
while curr:
if curr.value == find_val:
return True
if curr.value > find_val:
curr = curr.left
else:
curr = curr.right
return False
# Set up tree
tree = BST(4)
# Insert elements
tree.insert(2)
tree.insert(1)
tree.insert(3)
tree.insert(5)
# Check search
# Should be True
print(tree.search(4))
# Should be False
print(tree.search(6))