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