1
1
#binary tree using LinkedList
2
2
class Node :
3
- def __init__ (self , key ) :
4
- self .val = key
3
+ def __init__ (self , data ) :
4
+ self .data = data
5
5
self .left = None
6
6
self .right = None
7
7
@@ -12,15 +12,15 @@ def print_inorder(root):
12
12
print_inorder (root .left )
13
13
14
14
# print data of node
15
- print (root .val )
15
+ print (root .data , end = " " )
16
16
17
17
# recur on the right child
18
18
print_inorder (root .right )
19
19
20
20
def print_preorder (root ):
21
21
if root :
22
22
# first print data of node
23
- print (root .val )
23
+ print (root .data , end = " " )
24
24
25
25
# recur on left child
26
26
print_preorder (root .left )
@@ -38,7 +38,46 @@ def print_postorder(root):
38
38
print_postorder (root .right )
39
39
40
40
# print data of node
41
- print (root .val )
41
+ print (root .data , end = " " )
42
+
43
+ '''
44
+ 1) Create an empty stack S.
45
+ 2) Initialize current node as root
46
+ 3) Push the current node to S and set current = current->left until current is NULL
47
+ 4) If current is NULL and stack is not empty then
48
+ a) Pop the top item from stack.
49
+ b) Print the popped item, set current = popped_item->right
50
+ c) Go to step 3.
51
+ 5) If current is NULL and stack is empty then we are done.
52
+ '''
53
+ # iterative inorder traversal with stack
54
+ def in_order (root ):
55
+
56
+ # initialize current with root
57
+ current = root
58
+ # initialize stack
59
+ stack = []
60
+
61
+ while True :
62
+ # reach the leftmost node of the current node
63
+ if current is not None :
64
+ # add current node into the stack
65
+ stack .append (current )
66
+ # goto left of cuurent
67
+ current = current .left
68
+
69
+ # if current is empty and stack is not empty then
70
+ elif stack :
71
+ # pop out the stack element and make current to the popped out element
72
+ current = stack .pop ()
73
+ #print the popped item
74
+ print (current .data , end = " " )
75
+ # set current to right of popped item
76
+ current = current .right
77
+
78
+ # if current and stack both are empty then we are done
79
+ else :
80
+ break
42
81
43
82
44
83
root = Node (1 )
@@ -57,12 +96,18 @@ def print_postorder(root):
57
96
58
97
'''
59
98
60
- print ("Inorder TRaversal :" )
99
+ print ("Inorder Traversal using recursive method :" )
61
100
print_inorder (root )
101
+ print ()
62
102
63
- print ("Preorder Traversal" )
103
+ print ("Preorder Traversal using recursive method: " )
64
104
print_preorder (root )
105
+ print ()
65
106
66
- print ("Postorder Traversal" )
107
+ print ("Postorder Traversal using recursive method: " )
67
108
print_postorder (root )
109
+ print ()
68
110
111
+ print ("Inorder Traversal using iterative method: " )
112
+ in_order (root )
113
+ print ()
0 commit comments