8000 Create InorderTreeTraversal.py · AllAlgorithms/python@e090eda · GitHub
[go: up one dir, main page]

Skip to content

Commit e090eda

Browse files
kmehulyabranhe
authored andcommitted
Create InorderTreeTraversal.py
1 parent 337e300 commit e090eda

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
class Node:
2+
"""A binary tree 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+
"""Generator function for iterative inorder tree traversal"""
11+
12+
current = root
13+
14+
while current is not None:
15+
16+
if current.left is None:
17+
yield current.data
18+
current = current.right
19+
else:
20+
21+
# Find the inorder 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 child of its inorder predecessor
29+
pre.right = current
30+
current = current.left
31+
32+
else:
33+
# Revert the changes made in the 'if' part to restore the
34+
# original tree. i.e., fix the right child of predecessor
35+
pre.right = None
36+
yield current.data
37+
current = current.right
38+
39+
# Driver program to test the above function
40+
41+
root = Node(1,
42+
right = Node(3),
43+
left = Node(2,
44+
left = Node(4),
45+
right = Node(5)
46+
)
47+
)
48+
49+
for v in morris_traversal(root):
50+
print(v, end=' ')

0 commit comments

Comments
 (0)
0