Skip to content

added morris traversal algorithm #2537

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions traversals/morris_traversal.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""
Morris(InOrder) travaersal is a tree traversal algorithm that does not employ the use of recursion or a stack.
In this traversal, links are created as successors and nodes are printed using these links.
Finally, the changes are reverted back to restore the original tree.

"""



class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None



def Morris(root):
InorderTraversal = []
# set current to root of binary tree
curr = root

while(curr is not None):
if(curr.left is None):
InorderTraversal.append(curr.data)
curr = curr.right
else:
# find the previous (prev) of curr
prev = cur.left
while(prev.right is not None and prev.right != curr):
prev = prev.right

# make curr as right child of its prev
if(prev.right is None):
prev.right = curr
curr = curr.left

#firx the right child of prev
else:
prev.right = None
InorderTraversal.apend(curr.data)
curr = curr.right



root = Node(4)
temp = root
temp.left = Node(2)
temp.right = Node(8)
temp = temp.left
temp.left = Node(1)
temp.right = Node(5)

Morris(root)