Created
February 25, 2015 16:56
-
-
Save ptantiku/6e20e508a53ab4124df7 to your computer and use it in GitHub Desktop.
an implementation of binary tree in python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# binary tree in array | |
# | |
# author: ptantiku | |
# | |
class Node: | |
id = 0 | |
data = "" | |
# constructor | |
def __init__(self, id, data): | |
self.id = id | |
self.data = data | |
# toString | |
def __repr__(self): | |
return '(%d,%s)' % (self.id, self.data) | |
# print out tree | |
def printTree(tree): | |
index = 0 | |
level = 0 | |
while(index<len(tree)): | |
for i in range(2**level): | |
print(tree[index], ' ', end='') | |
index += 1 | |
if index>=len(tree): break | |
print(end='\n') | |
level += 1 | |
# trace-path from node's id(at leaf node) back to root | |
# using bottom-up style | |
def printPathTo(tree, id): | |
index=id #leaf id is already the index in array | |
while(index>=0): | |
print(tree[index]) | |
index = (index-1) >> 1 # get parent node | |
if __name__ == '__main__': | |
# initial an empty tree | |
tree = [] | |
# populate tree | |
print('populating the tree-----------------------------------') | |
for i in range(15): | |
obj = Node(i, chr(ord('A')+i)) | |
print(obj) | |
tree.append(obj) | |
# print array | |
print('print array-----------------------------------') | |
print(tree) | |
print('print tree-----------------------------------') | |
printTree(tree) | |
print('trace path(bottom-up)-----------------------------------') | |
printPathTo(tree, 13) #leaf id is alread the index of array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment