-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbst-practice.py
62 lines (52 loc) · 1.68 KB
/
bst-practice.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
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):
self.insert_node(self.root, Node(new_val))
def insert_node(self, start, new_node):
if new_node.value < start.value:
if start.left:
self.insert_node(start.left, new_node)
else:
start.left = new_node
else:
if start.right:
self.insert_node(start.right, new_node)
else:
start.right = new_node
def search(self, find_val):
return self.search_recursive(self.root, find_val)
def search_recursive(self, start, find_val):
if start:
if start.value > find_val:
self.search_recursive(start.left, find_val)
elif start.value < find_val:
self.search_recursive(start.right, find_val)
else:
return True
return False
def display(self):
return self.display_recursive(self.root)[:-1]
def display_recursive(self, start, traversal=""):
if start:
traversal = str(start.value) + "-" \
+ self.display_recursive(start.left, traversal) \
+ self.display_recursive(start.right, traversal)
return traversal
# 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))