LivingRobot
LivingRobot

Reputation: 913

Python Ordered List Preorder Tree Traversal

I'm new to python and am trying to return the preorder list of an ordered tree (NOTE: Not Binary Tree). I'm having some trouble following the recursion after it reaches a leaf of the tree. How do I get it to go back up to the previous node? Here's my code thus far:

def OrdPreOrder(T):
    if Is_OrdLeaf(T):
        return []
    else:
        for t in Subtrees(T):
            return [OrdRoot(t)] + OrdPreOrder(t)

Thanks in advance,

Upvotes: 0

Views: 878

Answers (1)

BigFatProgrammer
BigFatProgrammer

Reputation: 35

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.

Upvotes: 1

Related Questions