-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearchTree.py
More file actions
69 lines (51 loc) · 1.61 KB
/
binarySearchTree.py
File metadata and controls
69 lines (51 loc) · 1.61 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import random
class Node:
def __init__(self,value):
self.left = None
self.right = None
self.data = value
def addItem(self, toAdd):
if toAdd < self.data:
if self.left != None:
print("left:",self.left)
self.left.addItem(toAdd)
else:
self.left = Node(toAdd)
print("left:",self.left)
elif toAdd > self.data:
if self.right != None:
print("right:",self.right)
self.right.addItem(toAdd)
else:
self.right = Node(toAdd)
print("right:",self.right)
elif self.data == toAdd:
print(self)
return
def findItem(self, toFind):
if self.data == toFind:
return True
elif toFind < self.data:
if self.left != None:
#print(self.left)
x = self.left.findItem(toFind)
else:
return False
else:
if self.right != None:
#print(self.right)
x = self.right.findItem(toFind)
else:
return False
return x
def __str__(self) -> str:
return f"{self.data}"
test = [random.randint(1,10000) for i in range(5000)]
Tree = Node(test[0])
print(Tree)
for i in range(1,len(test)):
Tree.addItem(test[i])
print(sorted(test))
for i in range(100):
toFind = random.randint(1,10000)
print(toFind,": ",Tree.findItem(toFind))