-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-search-tree.py
55 lines (48 loc) · 1.38 KB
/
binary-search-tree.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
#Binary search tree (BST) practice from Udacity course "Data Structures and Algorithms in Python"
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):
start = self.root
while start:
if new_val < start.value:
if start.left != None:
start = start.left
else:
newNode = Node(new_val)
start.left = newNode
break
elif new_val > start.value:
if start.right != None:
start = start.right
else:
newNode = Node(new_val)
start.right = newNode
break
def search(self, find_val):
start = self.root
while start:
if find_val == start.value:
return True
elif find_val < start.value:
start = start.left
elif find_val > start.value:
start = start.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)