[英]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). 我是python的新手,正在尝试返回有序树的预排序列表(注意:不是二叉树)。 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,
预顺序遍历方法1.首先打印存储在节点2中的值,然后打印存储在子级中的值(根据某些原理)首先,
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). 我也不熟悉Python中的数据结构(代码中可能有错误)。 But hopefully it might point you in the right direction.
但是希望它可以为您指明正确的方向。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.