现实世界的前序/后序树遍历示例

发布于 2024-09-15 19:19:27 字数 251 浏览 10 评论 0原文

我很了解前序、中序和后序树遍历算法。 (参考)。我了解一些用途:按顺序遍历二叉搜索树,预排序用于克隆树。但我一生都无法想出一个需要后序遍历才能完成的现实世界任务。

你能举个例子吗?还有:你能给我一些预购遍历的更好用途吗?

编辑:除了表达式树和 RPN 之外,谁能给我一个例子吗?这真的是所有后购都有好处吗?

I understand pre-order, in-order, and post-order tree traversal algorithms just fine. (Reference). I understand a few uses: in-order for traversing binary search trees in order, pre-order for cloning a tree. But I can't for the life of me come up with a real world task that I'd need post-order traversal to accomplish.

Can you give me an example? And: can you give me any better uses for pre-order traversal?

Edit: Can anyone give me an example other than expression trees and RPN? Is that really all post-order is good for?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

戴着白色围巾的女孩 2024-09-22 19:19:27

拓扑排序是树(或有向无环图)的后序遍历。

这个想法是,图的节点代表任务,从 AB 的边表示 A 必须在 之前执行B。拓扑排序会将这些任务按顺序排列,使得任务的所有依赖项出现早于任务本身。任何构建系统(例如 UNIX make)都必须实现此算法。

达里奥提到的例子——通过手动内存管理销毁树的所有节点——就是这个问题的一个例子。毕竟,销毁节点的任务取决于其子节点的销毁。

Topological sorting is a post-order traversal of trees (or directed acyclic graphs).

The idea is that the nodes of the graph represent tasks and an edge from A to B indicates that A has to be performed before B. A topological sort will arrange these tasks in a sequence such that all the dependencies of a task appear earlier than the task itself. Any build system like UNIX make has to implement this algorithm.

The example that Dario mentioned — destroying all nodes of a tree with manual memory management — is an instance of this problem. After all, the task of destroying a node depends on the destruction of its children.

三生一梦 2024-09-22 19:19:27

正如 Henk Holterman 指出的那样,使用手动内存管理销毁树通常是后序遍历。

伪代码:

destroy(node) {
  if (node == null) return;

  destroy(node.left)
  destroy(node.right)

  // Post-order freeing of current node
  free(node)
}

As Henk Holterman pointed out, destroying a tree using manual memory management usually is a post-order traversal.

Pseudocode:

destroy(node) {
  if (node == null) return;

  destroy(node.left)
  destroy(node.right)

  // Post-order freeing of current node
  free(node)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文