The question is not very clear to me, but hopefully this will help.
You want to do a pre-order traversal of an ordered tree.
Pre-Order traversal means
1. Firstly print the value stored in node
2. Then print the value stored in children (according to some principle)
First off,
How do I get it to go back up to the previous node?
According to the definition of pre-order traversal i have written above, I don't see why you need to go back and revisit the parent node.
class Node:
def __init__(self, data):
self.__data = data
self.__children = []
def identifier(self):
return self.__data
def children(self):
return self.__children
def add_child(self, data):
self.__children.append(data)
class Tree:
def __init__(self):
self.__nodes = {}
def nodes(self):
return self.__nodes
def add_node(self, data, parent=None):
node = Node(data)
self[data] = node
if parent is not None:
self[parent].add_child(data)
return node
def traversal(tree):
if tree == None:
return
print (tree.identifier())
for child in tree.children():
traversal(child)
I am also not that well versed with data structures in Python (there might be mistakes in the code). But hopefully it might point you in the right direction.
how do I get it to go back up to the previous node?: recursion does that for you. I assume you know how pre-order visits the tree (i.e. the current node, then the children)T) is empty (e.g.None) and return if it is. If it is not, do something with the node contents then visit the children/subtrees.