Introduction to Binary Trees - Part 1

preview_player
Показать описание
An introduction to binary trees stored as a list and tree traversals.
Рекомендации по теме
Комментарии
Автор

bintree_print.py
```
import math


# Print List-based Binary Tree
def _plt_recursion(datalist, level=0, index=0, width=80):
num_on_level = 2**level
term_i = 0
print(level, end="")
for i in range(num_on_level):
val = datalist[index]
pos = (i+1) * (width / (num_on_level + 1))
glyph = "("+str(val)+")"
multiplier = math.floor(pos - term_i - len(glyph)/2)
term_i += multiplier + len(glyph)
padding = " " * multiplier
print(padding + glyph, end="")
index += 1
if index >= len(datalist):
break
print()
print("-"*width)
if index < len(datalist):
_plt_recursion(datalist, level+1, index, width)

def print_list_tree(datalist, width=80):
print("="*width)
_plt_recursion(datalist, 0, 0, width)


# Print Node-based Binary Tree
def _pnt_recursion(tree, level=0, index=0, width=80):
num_on_level = 2**level
term_i = 0
print(level, end="")
for i in range(num_on_level):
val = tree.get(index)
pos = (i+1) * (width / (num_on_level + 1))
glyph = "("+str(val)+")"
multiplier = math.floor(pos - term_i - len(glyph)/2)
term_i += multiplier + len(glyph)
padding = " " * multiplier
print(padding + glyph, end="")
index += 1
if index >= len(tree):
break
print()
print("-"*width)
if index < len(tree):
_pnt_recursion(tree, level+1, index, width)

def print_node_tree(tree, width=80):
print("="*width)
_pnt_recursion(tree, 0, 0, width)
```

LukeBeenJammin