开发者

how to print trees onto console?

it would be开发者_运维问答 nice if i could print the binary search trees i am writing onto python console ? any idea how to do it?


You can use something like this:

def printTree(tree, depth = 0):
    if tree == None or len(tree) == 0:
        print "\t" * depth, "-"
    else:
        for key, val in tree.items():
            print "\t" * depth, key
            printTree(val, depth+1)

(Source: http://www.siafoo.net/snippet/91)

This method will yield:

n1
    n2
        n4
        n5
    n3
        n6
        n7

You can go along these lines and prettify as necessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜