在Python中打印Tree数据结构

发布于 2021-01-29 17:16:22

我一直在寻找树打印的可能实现,该树打印以用户友好的方式打印树,而不是作为对象的实例。

我在网上遇到了这个解决方案:

来源:http//cbio.ufs.ac.za/live_docs/nbn_tut/trees.html

class node(object):
    def __init__(self, value, children = []):
        self.value = value
        self.children = children

    def __repr__(self, level=0):
        ret = "\t"*level+repr(self.value)+"\n"
        for child in self.children:
            ret += child.__repr__(level+1)
        return ret

此代码通过以下方式打印树:

'grandmother'
    'daughter'
        'granddaughter'
        'grandson'
    'son'
        'granddaughter'
        'grandson'

是否有可能获得相同的结果但不更改__repr__方法,因为我将其用于其他目的。

编辑:

解决方案,无需修改__repr____str__

def other_name(self, level=0):
    print '\t' * level + repr(self.value)
    for child in self.children:
        child.other_name(level+1)
关注者
0
被浏览
157
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    是的,将__repr__代码移至__str__,然后调用str()您的树或将其传递给print语句。记住也要__str__在递归调用中使用:

    class node(object):
        def __init__(self, value, children = []):
            self.value = value
            self.children = children
    
        def __str__(self, level=0):
            ret = "\t"*level+repr(self.value)+"\n"
            for child in self.children:
                ret += child.__str__(level+1)
            return ret
    
        def __repr__(self):
            return '<tree node representation>'
    

    演示:

    >>> root = node('grandmother')
    >>> root.children = [node('daughter'), node('son')]
    >>> root.children[0].children = [node('granddaughter'), node('grandson')]
    >>> root.children[1].children = [node('granddaughter'), node('grandson')]
    >>> root
    <tree node representation>
    >>> str(root)
    "'grandmother'\n\t'daughter'\n\t\t'granddaughter'\n\t\t'grandson'\n\t'son'\n\t\t'granddaughter'\n\t\t'grandson'\n"
    >>> print root
    'grandmother'
        'daughter'
            'granddaughter'
            'grandson'
        'son'
            'granddaughter'
            'grandson'
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看