Printing a tree in Python is easy if the parent-child relationship should not be visualized as well, i.e. just printing all nodes with an indentation that depends on the level within the tree.
To keep the code easy, let’s first define a simple tree structure by creating a Node class that holds a value x and can have an arbitrary number of child nodes:
class Node(object): def __init__(self, x, children=): self.x = x self.children = children
To print all nodes of a tree using depth-first search, only few lines are required:
def printTree(root, level=0): print(" " * level, root.x) for child in root.children: printTree(child, level + 1) #tree = Node(..., children=[Node(...., ...), Node(...,....)] # See end of the article for a bigger structure that is used for the examples in this article. printTree(tree)
However, the output can be hard to read. When the tree has more than a few levels, it is challenging to see the relationship between parent and child nodes. A definition of the following tree is given at the end of this article if you want to try it yourself. For now, just focus on the output:Read More