Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion Programs/P43_BinarySearchTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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()
Expand Down
21 changes: 21 additions & 0 deletions Programs/P62_BinaryTree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down