pythonpython-2.7printingtree

Printing a Tree data structure in Python


I was looking for a possible implementation of tree printing, which prints the tree in a user-friendly way, and not as an instance of object.

I came across this solution on the net:

Source: 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

This code prints the tree in the following way:

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

Is it possible to have the same result but without changing the __repr__ method, because I am using it for another purpose.


Solution

  • Yes, move the __repr__ code to __str__, then call str() on your tree or pass it to the print statement. Remember to use __str__ in the recursive calls too:

    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>'
    

    Demo:

    >>> 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'