File tree 1 file changed +50
-0
lines changed
Filter options
1 file changed +50
-0
lines changed
Original file line number Diff line number Diff line change
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 = ' ' )
You can’t perform that action at this time.
0 commit comments