In [ ]:
import logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
In [1]:
#Create node class
class Tree(object):
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def __repr__(self):
left = None if self.left is None else self.left.data
right = None if self.right is None else self.right.data
return '(D:{}, L:{}, R:{})'.format(self.data, left, right)
#Build the breadth first function
def build_tree_breadth_first(sequence):
# Create a list of trees
forest = [Tree(x) for x in sequence]
# Fix up the left- and right links
count = len(forest)
for index, tree in enumerate(forest):
left_index = 2 * index + 1
if left_index < count:
tree.left = forest[left_index]
right_index = 2 * index + 2
if right_index < count:
tree.right = forest[right_index]
for index, tree in enumerate(forest):
print('[{}]: {}'.format(index, tree))
return forest[0] # root
#Build the tree function
def tree():
root = build_tree_breadth_first(data)
print ('Root is:', root)
In [4]:
#Insert 15 random values
data = [3, 5, 2, 1, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
#Build tree and print breadth first
tree()