Skip to content

Commit e96796c

Browse files
committed
Adding a binary search tree.
1 parent e551d16 commit e96796c

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

bynary_tree/bst.py

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
class Node:
2+
def __init__(self, label):
3+
self.label = label
4+
self.left = None
5+
self.right = None
6+
7+
def getLabel(self):
8+
return self.label
9+
10+
def setLabel(self, label):
11+
self.label = label
12+
13+
def getLeft(self):
14+
return self.left
15+
16+
def setLeft(self, left):
17+
self.left = left
18+
19+
def getRight(self):
20+
return self.right
21+
22+
def setRight(self, right):
23+
self.right = right
24+
25+
class BinarySearchTree:
26+
def __init__(self):
27+
self.root = None
28+
29+
def insert(self, label):
30+
node = Node(label)
31+
32+
if self.empty():
33+
self.root = node
34+
else:
35+
36+
dad_node = None
37+
curr_node = self.root
38+
39+
while True:
40+
41+
if curr_node != None:
42+
43+
dad_node = curr_node
44+
45+
if node.getLabel() < curr_node.getLabel():
46+
curr_node = curr_node.getLeft()
47+
else:
48+
curr_node = curr_node.getRight()
49+
else:
50+
51+
if node.getLabel() < dad_node.getLabel():
52+
dad_node.setLeft(node)
53+
else:
54+
dad_node.setRight(node)
55+
56+
break
57+
58+
def empty(self):
59+
if self.root == None:
60+
return True
61+
return False
62+
63+
def show(self, curr_node):
64+
65+
if curr_node != None:
66+
print('%d' % curr_node.getLabel(), end=' ')
67+
self.show(curr_node.getLeft())
68+
self.show(curr_node.getRight())
69+
70+
def getRoot(self):
71+
return self.root
72+
73+
t = BinarySearchTree()
74+
t.insert(8)
75+
t.insert(3)
76+
t.insert(1)
77+
t.insert(6)
78+
t.insert(4)
79+
t.insert(7)
80+
t.insert(10)
81+
t.insert(14)
82+
t.insert(13)
83+
84+
t.show(t.getRoot())

0 commit comments

Comments
 (0)