任何人都可以指出我在伪代码中进行迭代深度优先树遍历,可以在订单前后对每个节点执行操作吗?
也就是说,在进入节点的孩子之前的行动,然后是从孩子们上升后的行动?
此外,我的树不是二进制 - 每个节点都有0..n个孩子。
基本上,我的情况是转换递归遍历,我在当前节点上执行前后操作,在递归到子节点的任一侧。
答案 0 :(得分:10)
我的计划是使用两个堆栈。一个用于预订遍历,另一个用于后序遍历。
现在,我运行标准的迭代DFS(深度优先遍历),并且只要我从{pre“堆栈pop
我将其推入”post“堆栈。
最后,我的“post”堆栈将在顶部具有子节点,在底部具有根节点。
treeSearch(Tree root) {
Stack pre;
Stack post;
pre.add(root);
while (pre.isNotEmpty()) {
int x = pre.pop();
// do pre-order visit here on x
post.add(x);
pre.addAll(getChildren(x));
}
while (post.isNotEmpty()) {
int y = post.pop();
// do post-order visit here on y
}
}
root
将始终从post
堆栈遍历,因为它将保持在底部。
这是简单的java代码:
public void treeSearch(Tree tree) {
Stack<Integer> preStack = new Stack<Integer>();
Stack<Integer> postStack = new Stack<Integer>();
preStack.add(tree.root);
while (!preStack.isEmpty()) {
int currentNode = preStack.pop();
// do pre-order visit on current node
postStack.add(currentNode);
int[] children = tree.getNeighbours(currentNode);
for (int child : children) {
preStack.add(child);
}
}
while (!postStack.isEmpty()) {
int currentNode = postStack.pop();
// do post-order visit on current node
}
}
我假设这是一棵树,所以:没有循环并且再没有重新访问同一个节点。但是,如果我们想要,我们总是可以拥有一个访问过的数组并检查它。
答案 1 :(得分:5)
我意识到这篇文章已经有好几年了,但没有一个答案似乎能直接回答这个问题,所以我想我会写一些简单的东西。
这假设一个整数索引图;但你必须根据需要调整它。迭代地执行DFS并且仍然具有预订/后序操作的关键是不要一次追加每个子项,而是完全像递归DFS一样,这只是添加一个孩子-node一次到堆栈,只有在完成后才从堆栈中删除它们。我通过创建一个包含邻接列表作为堆栈的包装器节点来完成此示例。如果您希望允许循环,则省略循环检查(无论如何它都不会遍历被访问的节点,因此它仍然可以工作)
class Stack(object):
def __init__(self, l=None):
if l is None:
self._l = []
else:
self._l = l
return
def pop(self):
return self._l.pop()
def peek(self):
return self._l[-1]
def push(self, value):
self._l.append(value)
return
def __len__(self):
return len(self._l)
class NodeWrapper(object):
def __init__(self, graph, v):
self.v = v
self.children = Stack(graph[v])
return
def iterative_postorder(G, s):
onstack = [False] * len(G)
edgeto = [None] * len(G)
visited = [False] * len(G)
st = Stack()
st.push(NodeWrapper(G, s))
while len(st) > 0:
vnode = st.peek()
v = vnode.v
if not onstack[v]:
print "Starting %d" % (v)
visited[v] = True
onstack[v] = True
if len(vnode.children) > 0:
e = vnode.children.pop()
if onstack[e]:
cycle = [e]
e = v
while e != cycle[0]:
cycle.append(e)
e = edgeto[e]
raise StandardError("cycle detected: %s, graph not acyclic" % (cycle))
if not visited[e]:
edgeto[e] = v
st.push(NodeWrapper(G, e))
else:
vnode = st.pop()
onstack[vnode.v] = False
print 'Completed %d' % (vnode.v)
答案 2 :(得分:3)
class Node:
def __init__( self, value ):
self.value = value
self.children = []
def preprocess( node ):
print( node.value )
def postprocess( node ):
print( node.value )
def preorder( root ):
# Always a flat, homogeneous list of Node instances.
queue = [ root ]
while len( queue ) > 0:
a_node = queue.pop( 0 )
preprocess( a_node )
queue = a_node.children + queue
def postorder( root ):
# Always a flat, homogeneous list of Node instances:
queue = [ root ]
visited = set()
while len( queue ) > 0:
a_node = queue.pop( 0 )
if a_node not in visited:
visited.add( a_node )
queue = a_node.children + [ a_node ] + queue
else:
# this is either a leaf or a parent whose children have all been processed
postprocess( a_node )
答案 3 :(得分:1)
我认为通过在El Mariachi提供的后序功能中插入preProcess,我可以得到我所需要的:
def postorder( root ):
# Always a flat, homogeneous list of Node instances:
queue = [ root ]
visited = set()
while len( queue ) > 0:
a_node = queue.pop( 0 )
if a_node not in visited:
preprocess( a_node ) # <<<<<<<< Inserted
visited.add( a_node )
queue = a_node.children + [ a_node ] + queue
else:
# this is either a leaf or a parent whose children have all been processed
postprocess( a_node )
答案 4 :(得分:1)
我希望你觉得它很有用。
http://www.vvlasov.com/2013/07/post-order-iterative-dfs-traversal.html
代码:
public void dfsPostOrderIterative(AdjGraph graph, AdjGraph.Node vertex, Callback callback) {
Stack<Level> toVisit = new Stack<Level>();
toVisit.push(new Level(Collections.singletonList(vertex)));
while (!toVisit.isEmpty()) {
Level level = toVisit.peek();
if (level.index >= level.nodes.size()) {
toVisit.pop();
continue;
}
AdjGraph.Node node = level.nodes.get(level.index);
if (!node.isVisited()) {
if (node.isChildrenExplored()) {
node.markVisited();
callback.nodeVisited(graph, node);
level.index++;
} else {
List<AdjGraph.Node> edges = graph.edges(node);
List<AdjGraph.Node> outgoing = Lists.newArrayList(Collections2.filter(edges, new Predicate<AdjGraph.Node>() {
@Override
public boolean apply(AdjGraph.Node input) {
return !input.isChildrenExplored();
}
}));
if (outgoing.size() > 0)
toVisit.add(new Level(outgoing));
node.markChildrenExplored();
}
} else {
level.index++;
}
}
}
答案 5 :(得分:1)
一个简单的python实现,有两个不同的访问者
class Print_visitor(object):
def __init__(self):
pass
def pre_visit(self, node):
print "pre: ", node.value
def post_visit(self, node):
print "post:", node.value
class Prettyprint_visitor(object):
def __init__(self):
self.level=0
def pre_visit(self, node):
print "{}<{}>".format(" "*self.level, node.value)
self.level += 1
def post_visit(self, node):
self.level -= 1
print "{}</{}>".format(" "*self.level, node.value)
class Node(object):
def __init__(self, value):
self.value = value
self.children = []
def traverse(self, visitor):
visitor.pre_visit(self)
for child in self.children:
child.traverse(visitor)
visitor.post_visit(self)
if __name__ == '__main__':
#test
tree = Node("root")
tree.children = [Node("c1"), Node("c2"), Node("c3")]
tree.children[0].children = [Node("c11"), Node("c12"), Node("c13")]
tree.children[1].children = [Node("c21"), Node("c22"), Node("c23")]
tree.children[2].children = [Node("c31"), Node("c32"), Node("c33")]
tree.traverse(Print_visitor())
tree.traverse(Prettyprint_visitor())
答案 6 :(得分:1)
在尝试不同的解决方案失败之后,让我为迭代解决方案添加伪代码,在该迭代解决方案中,您实际上在堆栈变量中重新创建了函数调用堆栈空间(在递归版本中可能会溢出)。
您需要存储的所有状态是顶点编号和已处理的邻居数量。无论您的语言允许什么,它都可以是一个元组,一个列表,一个对象。
此解决方案的优点是您不会出现堆栈溢出,它也适用于具有周期的图,并且非常健壮。如果使用邻接表或矩阵,则获取下一个邻居很容易。
这是伪代码,因为它更易于理解,您不仅会从SO复制代码,对吗?
globals: isProcessed, preOrder, postOrder
depthFirstSearch()
set isProcessed to all false
for each vertex
if !isProcessed(vertex)
explore(vertex)
explore(root)
create stack
add (root, 0) to stack
visited = empty list
// a list of visited vertices e.g. for finding connected components
while stack is not empty
(vertex, processedNeighbors) ← pop from stack
if !isProcessed(vertex)
// previsit
add vertex to preOrder list
isProcessed(vertex) ← true
if processedNeighbors < number of vertex's neighbors
nextNeighborNumber ← processedNeighbors + 1
push (vertex, nextNeighborNumber) to stack
nextNeighbor ← 'nextNeighborNumber'th neighbor of vertex
if !isProcessed(nextNeighbor)
push (nextNeighbor, 0) to stack
else
// postvisit
add vertex to postOrder list