diff --git a/traversals/morris_traversal.py b/traversals/morris_traversal.py new file mode 100644 index 000000000000..25bc20fc4fd6 --- /dev/null +++ b/traversals/morris_traversal.py @@ -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)