通过修改morris遍历实现PreOrder和PostOrder遍历
morris 遍历非常适合 O(n) 时间和 O(1) 空间的 InOrder 遍历。是否有可能仅通过改变一些东西就可以使用相同的算法实现 PreOrder 和 PostOrder 遍历。
The morris traversal works great for InOrder traversal with O(n) time and O(1) space. Is it possible to just by changing a few things achieve PreOrder and PostOrder traversal using the same algorithm.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
我认为我们不能使用线程实现后序。
按照后序,我们必须遍历两个孩子,然后遍历他们的父母。
我们可以建立从子节点到父节点的链接,但之后我们无法向上移动这个父节点,因为它们没有链接。(一个指向左子节点,一个指向其右子节点,没有一个向上指向)
我们可以在 4 的右节点创建一个线程指向节点 5 。
我们可以在 5 的右侧节点创建一个指向节点 2 的线程。
但在节点 2 处,没有空指针来创建任何线程。节点 2 已经有指向节点 4 和节点 4 的指针。 5.
I dont think we can Implement post order using threads .
In post order we have to traverse both the children then their parent.
We can establish a link from child to parent, but after that we cant go up this parent coz their are no links.(one points to left child and one to its right child none pointing upwards)
we can create a thread at 4's right node pointing to node 5 .
We can create a thread at 5's right node pointing to node 2 .
But at node 2 there are no empty pointers to create any threads. Node 2 already has its pointers pointing to node 4 & 5.
我知道使用 morison Algo 进行预购的解决方案。
这是java代码
I know the solution for Preorder using morison Algo.
here is the java Code
后序可以通过简单地反转中序Morris算法来实现。解释一下,
按顺序 python Morris 实现:
对于后序,从 current 开始,如果 current.right 为空 - 开始向左看。如果不是,则找到最左边的前驱并将该前驱的左侧链接回当前。
(简而言之,按顺序从左向右翻转,并继续将节点插入到访问列表的开头;))
后序 Python Morris
Post-order can be achieved by simply reversing the in-order Morris algorithm. To explain,
In-order python Morris implementation:
For post-order, begin with current and if current.right is empty - start looking towards left. If not, find left most predecessor and link the left of this predecessor back to current.
(In short, flip the lefts in in-order to rights and keep inserting nodes to the beginning of the visited list ;) )
Post-order Python Morris
以下是使用修改后的莫里斯遍历进行前序遍历的示例代码。
可以用类似的方式修改右前驱的左链接进行后序遍历。
我没有时间测试代码。如果这段代码有问题,请告诉我。
Here is the sample code for pre order traversal using modified morris traversal.
You can use in a similar way to modify the right predecessor's left link for post order traversal.
I didn't get time to test the code. Please let me know if something is wrong in this code.
/没有堆栈和递归的 PreOrder 实现/
/PreOrder Implementation Without stack and recursion/
前序遍历上面已经回答了。
对于后序遍历,答案也是“是”。
您需要的唯一修改是:
1、当前驱的右子节点为当前节点时,将右子节点置为空,反向输出当前节点左子节点到前驱的所有节点。
2. 设置一个虚拟节点,并将其左子节点设置为树的根。
Java代码编写如下:
The preorder traversal has been answered above.
For the postorder traversal, the answer is "Yes" as well.
The only modifications you need are:
1. When the right child of the predecessor is current node, set the right child to null and reversely output all the nodes from the left child of the current node to the predecessor.
2. Set up a dummy node and set its left child to the root of the tree.
The Java code is written here: