class BinaryTree(object):
def __init__(self, rootObj):
self.key = rootObj
self.leftChild = None
self.rightChild = None
def insertLeftChild(self, newNode):
if self.leftChild == None:
self.leftChild = BinaryTree(newNode)
else:
newBinaryTree = BinaryTree(newNode)
newBinaryTree.leftChild = self.leftChild
self.leftChild = newBinaryTree
return self.leftChild
def insertRightChild(self, newNode):
if self.rightChild == None:
self.rightChild = BinaryTree(newNode)
else:
newBinaryTree = BinaryTree(newNode)
newBinaryTree.rightChild = newNode
self.rightChild = newBinaryTree
return self.rightChild
def getRoot(self):
return self.key
def setRoot(self, obj):
self.key = obj
def getLeftChild(self):
return self.leftChild
def getRightChild(self):
return self.rightChild
def __str__(self):
return '%s' % self.key
# DFS traversal techniques.
@classmethod
def preorder(cls, node):
if node == None: return False
print node
cls.preorder(node.getLeftChild())
cls.preorder(node.getRightChild())
@classmethod
def inorder(cls, node):
if node == None: return False
cls.inorder(node.getLeftChild())
print node
cls.inorder(node.getRightChild())
@classmethod
def postorder(cls, node):
if node == None: return False
cls.inorder(node.getLeftChild())
cls.inorder(node.getRightChild())
print node
def buildTree():
root = BinaryTree('a')
firstLeft = root.insertLeftChild('b')
firstRight = root.insertRightChild('c')
firstLeft.insertRightChild('d')
firstRight.insertLeftChild('e')
firstRight.insertRightChild('f')
return root
if __name__ == '__main__':
binaryTree = buildTree()
print 'Preorder'
print BinaryTree.preorder(binaryTree)
print 'Inorder'
print BinaryTree.inorder(binaryTree)
print 'Postorder'
print BinaryTree.postorder(binaryTree)
|
||||
As evidenced by the bug in Rev 1, the inconsistent naming between Getters and setters would be better done using the
Your traversal algorithms should not have a
A nice way to write simple unit tests and provide documentation at the same time is to use the |
|||||||||||||
|
A few comments:
|
|||||||||||||||||
|
There is a issue with how you are handling the payload for the tree. The property for it is called "Key" which is okay, but the constructor argument is calling it an object. So are we storing a value or a data structure? If it is a data structure, then payload would probably be a better name. I also see problems with the Insert methods. The argument named The If you want the |
||||
|
Don't repeat yourselfLet's refactor this original code step by step, simply by removing unnecessary repetitions and see where it gets us:
Notice that
Notice that
Follow the same logic in Strange namingIn Simplify the namesI think in a |
||||
|
unittest
specifically? Either way, there is plenty of documentation out there already. – jonrsharpe Oct 30 '14 at 11:01