我正在寻找一种非递归深度优先搜索算法,用于非二叉树。任何帮助都是非常感谢的。
发布于 2011-03-12 05:48:35
您将使用包含尚未访问的节点的stack:
stack.push(root)
while !stack.isEmpty() do
node = stack.pop()
for each node.childNodes do
stack.push(stack)
endfor
// …
endwhile
发布于 2011-03-13 04:53:06
如果您有指向父节点的指针,则无需额外内存即可完成此操作。
def dfs(root):
node = root
while True:
visit(node)
if node.first_child:
node = node.first_child # walk down
else:
while not node.next_sibling:
if node is root:
return
node = node.parent # walk up ...
node = node.next_sibling # ... and right
请注意,如果子节点存储为数组,而不是通过同级指针,则可以找到下一个同级节点:
def next_sibling(node):
try:
i = node.parent.child_nodes.index(node)
return node.parent.child_nodes[i+1]
except (IndexError, AttributeError):
return None
发布于 2011-03-12 05:34:30
使用堆栈跟踪节点
Stack<Node> s;
s.prepend(tree.head);
while(!s.empty) {
Node n = s.poll_front // gets first node
// do something with q?
for each child of n: s.prepend(child)
}
https://stackoverflow.com/questions/5278580
复制相似问题