Skip to content

Commit 4bd9377

Browse files
authored
Merge pull request BeeBombshell#114 from yashbhanu/main
Code for Morris Traversal in Binary Tree
2 parents 8385b62 + c72e2bc commit 4bd9377

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
2+
class Node:
3+
def __init__(self, data, left=None, right=None):
4+
self.data = data
5+
self.left = left
6+
self.right = right
7+
8+
9+
def morris_traversal(root):
10+
11+
current = root
12+
13+
while current is not None:
14+
15+
if current.left is None:
16+
yield current.data
17+
current = current.right
18+
else:
19+
20+
# Find the inorder
21+
# predecessor of current
22+
pre = current.left
23+
while pre.right is not None and pre.right is not current:
24+
pre = pre.right
25+
26+
if pre.right is None:
27+
28+
# Make current as right
29+
# child of its inorder predecessor
30+
pre.right = current
31+
current = current.left
32+
33+
else:
34+
# Revert the changes made
35+
pre.right = None
36+
yield current.data
37+
current = current.right
38+
39+
root = Node(1,right=Node(3),left=Node(2,left=Node(4),right=Node(5)))
40+
41+
for v in morris_traversal(root):
42+
print(v, end=' ')

0 commit comments

Comments
 (0)