码迷,mamicode.com
首页 > 编程语言 > 详细

python 实现树结构的打印

时间:2016-06-26 21:01:25      阅读:1049      评论:0      收藏:0      [点我收藏+]

标签:

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

打印效果如下:

技术分享

python 实现树结构的打印

标签:

原文地址:http://www.cnblogs.com/hans-201506/p/5618544.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!