Skip to content

Instantly share code, notes, and snippets.

@skuro
Created August 30, 2017 09:41
Show Gist options
  • Save skuro/b0cb734548cbd38a734f17065d5acad5 to your computer and use it in GitHub Desktop.
Save skuro/b0cb734548cbd38a734f17065d5acad5 to your computer and use it in GitHub Desktop.
comments
class TreeNode:
def __init__(self, key, val, left=None, right=None, parent=None):
# key e' inutile
self.key = key
self.payload = val
self.leftChild = left
self.rightChild = right
self.parent = parent
def hasLeftChild(self):
# Nota: questa e' una mia opinione:
# se la funzione si chiama "hasQualcosa" mi aspetto che ritorni un Boolean, meglio return self.leftChild != None
return self.leftChild
def hasRightChild(self):
# stesso commento di hasLeftChield
return self.rightChild
def isLeftChild(self):
return self.parent and self.parent.leftChild == self
def isRightChild(self):
return self.parent and self.parent.rightChild == self
def isRoot(self):
return not self.parent
def isLeaf(self):
# meglio usare self.isRightChild() or self.isLeftChild()
return not (self.rightChild or self.leftChild)
# meglio chiamarlo hasAnyChild, piu' corretto in inglese
def hasAnyChildren(self):
# anche qua, self.hasRightChield() or self.hasLeftChild()
return self.rightChild or self.leftChild
def hasBothChildren(self):
# commento simile che per hasAnyChildren()
return self.rightChild and self.leftChild
def replaceNodeData(self, val, key, lc, rc):
self.key = key
self.payload = val
self.leftChild = lc
self.rightChild = rc
if self.hasLeftChild():
self.leftChild.parent = self
if self.hasRightChild():
self.rightChild.parent = self
class BinarySearchTree:
def __init__(self):
self.root = None
self.size = 0
def length(self):
return self.size
def __len__(self):
return self.size
def __iter__(self):
return self.root.__iter__()
def insert(self, key, val):
if self.root:
self.insert_helper(key, val, self.root)
else:
self.root = TreNode(key, val)
def insert_helper(self, key, val, currentNode):
if key <= currentNode:
if currentNode.hasLeftChild():
self.insert_helper(key, val, currentNode.leftChild)
else:
currentNode.leftChild = TreeNode(key, val, parent = currentNode)
else:
if currentNode.hasRightChild():
self.insert_helper(key, val, currentNode.rightChild)
else:
currentNode.rightChild = TreeNode(key, val, parent = currentNode)
def search(self, data):
if self.data == data:
return self.data
elif:
if data < self.data:
return self.left.search(data)
else:
return self.right.search(data)
else:
print (data, 'not found')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment