Textual tree representation

From juliano.info

Jump to: navigation, search
Text tree example.png

This is something I need every once in a while, and I have to spend a few minutes remembering the algorithm every time. This time I decided to make this note so that I'll have it here the next time I need it.

This is usually called an ASCII tree, but that name would be inappropriate to this one since I used Unicode characters. There are many other similar algorithms around, this one is the one I use.

#!/usr/bin/python
# coding=utf-8
 
# tree characters
TC = [ u"   ", u" │ " ], [ u" └─", u" ├─" ]
 
# example tree structure
t = ( "root", [
        ( "branch %d"%(a), [
            ("leaf %d"%(b), []) for b in range(3)
        ] ) for a in range(3)
    ] )
 
def tree(r, brs=[]):
    """Print a textual tree representation of r and its children."""
    name, children = r
    if brs:
        print ' '.join(
            [ TC[0][b] for b in brs[:-1] ] + [ TC[1][brs[-1]] ]
        ),
    print name
    for r in children:
        tree(r, brs + [r is not children[-1]])
 
tree(t)
Views