diff --git a/Programs/P43_BinarySearchTree.py b/Programs/P43_BinarySearchTree.py index d82b433..eac303f 100644 --- a/Programs/P43_BinarySearchTree.py +++ b/Programs/P43_BinarySearchTree.py @@ -72,9 +72,13 @@ def postorder(self): print(str(self.data), end = ' ') class Tree(object): - def __init__(self): + def __init__(self, initial_data = []): self.root = None + # If provided, add initial data + for data in initial_data: + self.insert(data) + def insert(self, data): if self.root: return self.root.insert(data) @@ -106,6 +110,22 @@ def postorder(self): print('Postorder: ') self.root.postorder() + + def pprint(self, head_node=0, _pre="", _last=True, term=False): + + head_node = self.root if head_node == 0 else head_node + + data = "*" if head_node is None else head_node.data + + print(_pre, "`- " if _last else "|- ", data, sep="") + _pre += " " if _last else "| " + + if term: return + + for i, child in enumerate([head_node.leftChild, head_node.rightChild]): + self.pprint(child, _pre, bool(i) ,term=not(bool(child))) + + if __name__ == '__main__': tree = Tree() tree.insert(10) @@ -117,6 +137,7 @@ def postorder(self): tree.insert(7) tree.insert(15) tree.insert(13) + tree.pprint() print(tree.find(1)) print(tree.find(12)) tree.preorder() diff --git a/Programs/P62_BinaryTree.py b/Programs/P62_BinaryTree.py index fe29b3a..56a3bc1 100644 --- a/Programs/P62_BinaryTree.py +++ b/Programs/P62_BinaryTree.py @@ -38,18 +38,39 @@ def insertLeft(self,newnodeData): tree.left = self.left + + def printTree(tree): if tree != None: printTree(tree.getLeftChild()) print(tree.getnodeDataValue()) printTree(tree.getRightChild()) + +def pprint(head_node, _pre="", _last=True, term=False): + data = "*" if head_node is None else head_node.nodeData + + print(_pre, "`- " if _last else "|- ", data, sep="") + _pre += " " if _last else "| " + + if term: return + + left = head_node.getLeftChild() + right = head_node.getRightChild() + + for i, child in enumerate([left, right]): + pprint(child, _pre, bool(i) ,term=not(bool(child))) + + + + def testTree(): myTree = BinaryTree("1") myTree.insertLeft("2") myTree.insertRight("3") myTree.insertRight("4") printTree(myTree) + pprint(myTree) if __name__ == '__main__': testTree()