张祎

导航

python 实现树结构的打印

class TreeNode:
    def __init__(self,value):
        self.children = []
        self.value = value
 
    def add_child(self,*child):
        self.children+=child
 
    def show(self,layer):
        print  "  "*layer+self.value
        map(lambda child:child.show(layer+1),self.children)
 
 
def main():
    a1 = TreeNode("A-1")
    b1 = TreeNode("B-1")
    b2 = TreeNode("B-2")
    c1 = TreeNode("C-1")
    d1 = TreeNode("D-1")
    a1.add_child(b1,b2)
    b1.add_child(c1,TreeNode("C-2"))
    b2.add_child(TreeNode("C-3"),TreeNode("C-4"))
    c1.add_child(d1)
    d1.add_child(TreeNode("E-1"),TreeNode("E-2"))
    a1.show(0)
if __name__=="__main__":main()

来源于网络,http://www.cnblogs.com/wangfupeng1988/archive/2011/04/12/2013860.html

打印效果如下:

posted on 2016-06-26 20:51  张祎  阅读(1459)  评论(0编辑  收藏  举报