[英]Stack based modified preorder tree traversal
I have a recursive implementation of a modified preorder tree traversal ( nested set model ) that I want to implement without the use of recursion.我有一个修改的预序树遍历(嵌套集模型)的递归实现,我想在不使用递归的情况下实现它。
from collections import deque
def mptt_recurse(tree, node, preorder=None):
if node not in tree: return
if preorder is None: preorder = deque()
for child in tree[node]:
preorder.append(child)
mptt_recurse(tree, child, preorder)
preorder.append(child)
return preorder
The recursive implementation works as expected:递归实现按预期工作:
>>> tree = {
"root": ["food"],
"food": ["meat", "veg"],
"meat": ["pork", "lamb"],
"pork": ["bacon", "sausage"],
"lamb": ["cutlet"],
"soup": ["leak", "tomato"]
}
>>> mptt_recuser(tree, "root")
deque(['food', 'meat', 'pork', 'bacon', 'bacon', 'sausage', 'sausage', 'pork', 'lamb', 'cutlet', 'cutlet', 'lamb', 'meat', 'veg', 'veg', 'food'])
Each node appears twice with left and right values represented by the position in the deque
.每个节点出现两次,左右值由
deque
的位置表示。
def mptt_stack(tree, node):
if node not in tree: return
stack = deque(tree[node])
preorder = deque()
while stack:
node = stack.pop()
preorder.append(node)
if node not in tree:
continue
for child in reversed(tree[node]):
stack.append(child)
return preorder
With my stacked based implementation I have only been able to figure out how to get the preorder (not the modified preorder with both the left and right labels for each node) .通过我的基于堆叠的实现,我只能弄清楚如何获得预购(而不是每个节点的左右标签都经过修改的预购) 。
>>> mptt_stack(tree, "root")
deque(['food', 'meat', 'pork', 'bacon', 'sausage', 'lamb', 'cutlet', 'veg'])
Any pointers on a non recursive implementation would be great.关于非递归实现的任何指针都会很棒。
This will give the same results as mptt_recurse
.这将给出与
mptt_recurse
相同的结果。 It keeps an additional piece of information on the stack, which indicates whether it's entering or leaving the node:它在堆栈上保留一条额外的信息,表明它是进入还是离开节点:
def mptt_stack(tree, node):
if node not in tree: return
preorder = deque()
stack = []
for child in reversed(tree[node]):
stack.append([child, True])
while stack:
(node, first) = stack.pop()
preorder.append(node)
if first:
stack.append([node, False])
if node in tree:
for child in reversed(tree[node]):
stack.append([child, True])
return preorder
If you want to include the initial node in the result, you can replace the loop that initializes stack
with:如果要在结果中包含初始节点,可以将初始化
stack
的循环替换为:
stack = [[node, True]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.