public
Created

Build a binary tree in breadth-first style (BFS) using Python's treelib

  • Download Gist
bfs_treelib
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
from treelib import *
from treelib.tree import DuplicatedNodeIdError
from itertools import izip_longest
 
tree = Tree()
nums = range(1,8)
 
def grouper(n, iterable, fillvalue=None):
"grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return izip_longest(fillvalue=fillvalue, *args)
 
def i1(i):
return iter(i)
 
def i2(i):
return grouper(2, iter(i))
 
pos=i1(nums)
pos2=i2(nums[1:])
 
def append_children(e):
try:
for child in pos2.next():
tree.create_node(child, child, parent=e)
except StopIteration:
pass
 
for e in pos:
try:
tree.create_node(e, e)
except DuplicatedNodeIdError:
pass
append_children(e)
 
tree.show()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.