简体   繁体   中英

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,

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM