树的后序遍历不使用递归或栈递归、遍历

2023-09-11 02:39:43 作者:本姑娘赛过穆桂英

可能重复:   Post二叉树的遍历顺序没有递归

我要通过序遍历算法由莫里斯二叉树。 有人可以请建议是否有一种方法来遍历后序不使用递归和堆栈?

I was going through the inorder traversal algorithm in a binary tree by Morris. Can someone please suggest whether there is a way to traverse postorder without using recursion and stack?

推荐答案

您可以用螺纹树做。下面是该方法的概要(取自这里。—见幻灯片31):

You can do this with a threaded tree. Here's an outline of the method (taken from here—see slide 31):

后序:创建一个具有根为后代留下一个虚拟节点 系统变量可以用来检查当前的动作类型。 如果动作是左遍历当前节点有左后代,那么后代 遍历。否则,动作改为正确的穿越。 如果操作是正确的遍历和当前节点有左后裔,行动改变 向左穿越。否则,动作改为访问节点。 如果操作访问节点:当前节点的访问,之后它的后序的继任者 已被发现。 如果可以访问通过一个线程当前节点的父(即当前节点是父母的 左子),然后遍历被设置为继续父权后裔。 如果当前节点没有正确的后代,这是正确的扩展链的末端 的节点。 第一:所述链的开始是通过当前节点的螺纹达到 第二:链节点的正确引用反转 最后:链向后扫描,每个节点访问,然后右键引用 恢复到previous设置。 Postorder: a dummy node created that has root as left descendant. A variable can be used to check type of current action. If action is left traversal and current node has a left descendant, then descendant is traversed. Otherwise action changed to right traversal. If action is right traversal and current node has a left descendant, action changed to left traversal. Otherwise action changed to visiting a node. If action is visiting node: current node is visited, afterwards its postorder successor has to be found. If current node’s parent accessible through a thread (i.e. current node is parent’s left child) then traversal is set to continue with the right descendant of parent. If current node has no right descendant, this is the end of the right-extended chain of nodes. First: the beginning of the chain is reached through the thread of the current node. Second: right references of nodes in the chain is reversed. Finally: chain is scanned backward, each node is visited, then right references are restored to previous settings.

作为上述参考接着说明,它也可以不进行穿线如果使用临时修改树状结构

As the above reference goes on to show, it can also be done without threading if you use temporary modifications to the tree structure.