In [1]:
class TreeNode:
'''Class for a binary tree'''
def __init__(self, data):
'''
Constructor of a data node in the binary tree.
@param data data value of the node
'''
self.data = data
self.left = None
self.right = None
def insert(self, data):
'''
Function for inserting new data into the binary tree.
@param data data value of the node
'''
if self.data:
if data < self.data:
if self.left == None:
self.left = TreeNode(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right == None:
self.right = TreeNode(data)
else:
self.right.insert(data)
else:
self.data = data
def insertMany(self, datalist):
'''
Function for inserting new data into the binary tree.
@param data data value of the node
'''
for data in datalist:
if self.data:
if data < self.data:
if self.left == None:
self.left = TreeNode(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right == None:
self.right = TreeNode(data)
else:
self.right.insert(data)
else:
self.data = data
def getNode(self, data, parent = None):
'''
Function to get the node containing the data
@param data data value of the node
@param parent parent of the node
@return node and parent (or None)
'''
if data < self.data:
if self.left is None:
return None, None
else:
return self.left.getNode(data, parent = self)
elif data > self.data:
if self.right is None:
return None, None
else:
return self.right.getNode(data, parent = self)
else:
return self, parent
def deleteValue(self, data):
'''
Function to delete a value from the tree
@param data data value of the node
@param parent parent of the node
@return node and parent (or None)
'''
node, parent = self.getNode(data)
# Node has no children
# Handel root node (i.e. no parent) differently
if node.left is None and node.right is None:
if parent:
if parent.left is node:
parent.left = None
else:
parent.right = None
del node
else:
self.data = None
# Node has more than one child
elif node.left and node.right:
parent = node
successor = node.right
while successor.left:
parent = successor
successor = successor.left
node.data = successor.data
if parent.left == successor:
parent.left = successor.right
else:
parent.right = successor.right
# Node has one child
else:
if node.left:
n = node.left
else:
n = node.right
if parent:
if parent.left is node:
parent.left = n
else:
parent.right = n
del node
else:
self.left = n.left
self.right = n.right
self.data = n.data
def getAllValues(self):
if self.data:
if self.left:
self.left.getAllValues()
print(self.data)
if self.right:
self.right.getAllValues()
In [2]:
myTree = TreeNode(8)
myTree.insert(6)
myTree.insertMany([4, 7, 14, 13])
node, parent = myTree.getNode(6)
print(node.data)
print(parent.data)
print("")
myTree.getAllValues()
print("")
myTree.deleteValue(7)
myTree.getAllValues()