-3

I'm trying to print a tree, the problem is that I can't find any other way than printing it like this:

1
|__2
   |__3
      |__33
   |__4
|__22

But is there any way to print it like this:

      1
     / \
    2  22
   / \
  3   4
  |
  33

Here is my code:

class treeNode:

    def __init__(self,data):
        self.data = data
        self.children = []
        self.parent = None
        self.nextSibling = None
        self.level = 0
        self.prevSibling = None

Here, I created a class for the tree nodes, I know that the code is bad but I am still a beginner and I will improve it in the future. I used lists to store children and linked lists to sort siblings because it will be useful later when trying to print the actual tree.

    def add_children(self,*child):
        for i in child:
            i.parent = self
            self.children.append(i)
            if len(self.children) > 1:
                self.children[-2].nextSibling = i

class Tree:

    def __init__(self,root:treeNode):
        self.root = root
        self.depth = 0

    def print_tree(self):
        print(self.root.data)
        kid = self.root.children[0]
        while (kid != self.root):
            kid.level_func()
            print("  " * (kid.level - 1) * 2 + "|" + "__",kid.data)
            if len(kid.children) == 0:
                while kid.parent:
                    if kid.nextSibling:
                        kid = kid.nextSibling
                        break
                    else:
                        kid = kid.parent
            else:
                kid = kid.children[0]

The way I printed the tree is in this order: print current node, go to children if the current node has any kids, if not go to the current node 's parent 's next sibling and it will continue like that until it reaches the root.

Thanks in advance :)

1 Answers1

0

If your tree is a binary tree, the second form can be obtained using the printBTree function here

for example:

              80
          ___/  \___
        50          90
     __/  \__      /
   10        60  85
  /  \      /  \
 5    30  55    70
        \
         35

You could try to make a variant of it for a tree with multiple children but you will quickly run out of horizontal space.

for those trees, the indented format is preferable, although you could make it look a little better:

def printTree(node,nodeInfo,indent=""):
    label,children = nodeInfo(node)
    print(indent[:-3] + "|_ "*bool(indent) + str(label))
    for more,child in enumerate(children,1-len(children)):
        childIndent = "|  " if more else "   "
        printTree(child,nodeInfo,indent+childIndent)

Usage:

T = {'data': 1, 'children':
        [ { 'data':2, 'children':
            [ {'data':6 }, {'data':7} ]},
          {'data':3},
          {'data':4},
          {'data':5, 'children':
           [{'data':10}]}
        ]
     }

printTree(T,lambda d:(d['data'],d.get('children',[])))

1
|_ 2
|  |_ 6
|  |_ 7
|_ 3
|_ 4
|_ 5
   |_ 10

You could use printTree with your treeNode class like this:

printTree(myTree.root,lambda n:(n.data,n.children))
Alain T.
  • 40,517
  • 4
  • 31
  • 51