Real world pre/post-order tree traversal examples

天大地大妈咪最大 提交于 2019-12-02 18:29:49

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.

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)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!