11#binary tree using LinkedList
22class Node :
3- def __init__ (self , key ) :
4- self .val = key
3+ def __init__ (self , data ) :
4+ self .data = data
55 self .left = None
66 self .right = None
77
@@ -12,15 +12,15 @@ def print_inorder(root):
1212 print_inorder (root .left )
1313
1414 # print data of node
15- print (root .val )
15+ print (root .data , end = " " )
1616
1717 # recur on the right child
1818 print_inorder (root .right )
1919
2020def print_preorder (root ):
2121 if root :
2222 # first print data of node
23- print (root .val )
23+ print (root .data , end = " " )
2424
2525 # recur on left child
2626 print_preorder (root .left )
@@ -38,7 +38,46 @@ def print_postorder(root):
3838 print_postorder (root .right )
3939
4040 # 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
4281
4382
4483root = Node (1 )
@@ -57,12 +96,18 @@ def print_postorder(root):
5796
5897'''
5998
60- print ("Inorder TRaversal :" )
99+ print ("Inorder Traversal using recursive method :" )
61100print_inorder (root )
101+ print ()
62102
63- print ("Preorder Traversal" )
103+ print ("Preorder Traversal using recursive method: " )
64104print_preorder (root )
105+ print ()
65106
66- print ("Postorder Traversal" )
107+ print ("Postorder Traversal using recursive method: " )
67108print_postorder (root )
109+ print ()
68110
111+ print ("Inorder Traversal using iterative method: " )
112+ in_order (root )
113+ print ()
0 commit comments