File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change @@ -138,3 +138,47 @@ class Solution:
138138```
139139
140140如要实现前序、后序遍历,只需要调整左右子节点的入栈顺序即可。
141+
142+ ## Morris 遍历
143+
144+ 我们可以使用一种叫做 Morris 遍历的方法,既不使用递归也不借助于栈。从而在$O(1)$时间完成这个过程。
145+
146+ ``` python
147+ def MorrisTraversal (root ):
148+ curr = root
149+
150+ while curr:
151+ # If left child is null, print the
152+ # current node data. And, update
153+ # the current pointer to right child.
154+ if curr.left is None :
155+ print (curr.data, end = " " )
156+ curr = curr.right
157+
158+ else :
159+ # Find the inorder predecessor
160+ prev = curr.left
161+
162+ while prev.right is not None and prev.right is not curr:
163+ prev = prev.right
164+
165+ # If the right child of inorder
166+ # predecessor already points to
167+ # the current node, update the
168+ # current with it's right child
169+ if prev.right is curr:
170+ prev.right = None
171+ curr = curr.right
172+
173+ # else If right child doesn't point
174+ # to the current node, then print this
175+ # node's data and update the right child
176+ # pointer with the current node and update
177+ # the current with it's left child
178+ else :
179+ print (curr.data, end = " " )
180+ prev.right = curr
181+ curr = curr.left
182+ ```
183+
184+ 参考: [ what-is-morris-traversal] ( https://www.educative.io/edpresso/what-is-morris-traversal )
You can’t perform that action at this time.
0 commit comments