algorithm - 树遍历以层次优先顺序和深度优先顺序递归

标签 algorithm tree traversal

有没有什么算法可以先递归遍历树,后序非递归遍历。非常感谢。

最佳答案

要获得有效的递归广度优先搜索,您可以使用 iterative deepening depth-first search .它特别适用于分支因子较高的情况,在这种情况下,常规广度优先搜索往往会因内存消耗过多而窒息。

编辑: Marcos Marin already mentioned it ,但为了完整起见,the Wikipedia page on breadth-first traversal如此描述算法:

  1. Enqueue the root node.
  2. Dequeue a node and examine it.
    • If the element sought is found in this node, quit the search and return a result.
    • Otherwise enqueue any successors (the direct child nodes) that have not yet been discovered.
  3. If the queue is empty, every node on the graph has been examined – quit the search and return "not found".
  4. Repeat from Step 2.

Note: Using a stack instead of a queue would turn this algorithm into a depth-first search.

如果您想进行非递归深度优先遍历,那么最后一行显然对您很有趣。获得预购或后购只是修改您在步骤 2.b 中附加节点的方式的问题。

关于algorithm - 树遍历以层次优先顺序和深度优先顺序递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1569972/

相关文章:

algorithm - 使用 Fisher-Yates shuffle 从链表中获取 k 个随机值

d3.js - 避免 d3.js 中树形布局中的节点重叠

javascript - 使用键从集合动态创建树对象

java - 二叉树 : Method to return TRUE if all values equal a specific value

c - 遍历矩阵的相邻对角线

jquery - 如何在 jQuery 中找到具有指定类的最后一个连续 div?

c - 如何在 C 中生成正态分布的正整数?

c - 用于按给定月份,日期和给定月份的第一天查找日期的工作日的程序

java - Java 中的基本递归算法

python - 对于两个列表 l1 和 l2,如何在 python 中有效地检查所有 e1 ∈ l1, ∃p(e1,e2) 其中 e2 是 l2 中的某个元素?