Skip to content

Instantly share code, notes, and snippets.

@metaperl
Created August 28, 2013 18:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save metaperl/6369275 to your computer and use it in GitHub Desktop.
Save metaperl/6369275 to your computer and use it in GitHub Desktop.
Build a binary tree in breadth-first style (BFS) using Python's treelib
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment