Python/data_structures/Binary Tree/binary_seach_tree.py

104 lines
1.9 KiB
Python
Raw Normal View History

'''
A binary search Tree
'''
2017-07-04 16:46:46 +00:00
class Node:
def __init__(self, label):
self.label = label
self.left = None
2017-10-10 00:05:14 +00:00
self.right = None
def getLabel(self):
return self.label
def setLabel(self, label):
2017-06-30 19:12:10 +00:00
self.label = label
def getLeft(self):
return self.left
def setLeft(self, left):
self.left = left
def getRight(self):
2017-10-10 00:05:14 +00:00
return self.right
def setRight(self, right):
2017-10-10 00:05:14 +00:00
self.right = right
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, label):
2017-07-04 16:46:46 +00:00
# Create a new Node
node = Node(label)
if self.empty():
self.root = node
else:
dad_node = None
curr_node = self.root
while True:
2017-07-04 16:46:46 +00:00
if curr_node is not None:
dad_node = curr_node
if node.getLabel() < curr_node.getLabel():
curr_node = curr_node.getLeft()
else:
curr_node = curr_node.getRight()
else:
if node.getLabel() < dad_node.getLabel():
dad_node.setLeft(node)
else:
dad_node.setRight(node)
break
def empty(self):
2017-07-04 16:46:46 +00:00
if self.root is None:
return True
return False
def preShow(self, curr_node):
2017-07-07 17:08:04 +00:00
if curr_node is not None:
2017-06-20 07:17:20 +00:00
print(curr_node.getLabel(), end=" ")
self.preShow(curr_node.getLeft())
self.preShow(curr_node.getRight())
def getRoot(self):
return self.root
2017-06-21 03:44:26 +00:00
'''
Example
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
'''
t = BinarySearchTree()
t.insert(8)
t.insert(3)
t.insert(1)
t.insert(6)
t.insert(4)
t.insert(7)
t.insert(10)
t.insert(14)
t.insert(13)
t.preShow(t.getRoot())