From bb38e004272aeee9b7246ab653a91f69eecd88ed Mon Sep 17 00:00:00 2001 From: Siddharth Choudhary <60484636+siddharthzs@users.noreply.github.com> Date: Thu, 1 Oct 2020 00:57:02 +0530 Subject: [PATCH] added morris traversal algorith Morris Traversal is a tree traversal algorithm to traverse tree without using any stack or queue. --- traversals/morris_traversal.py | 54 ++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 traversals/morris_traversal.py 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)