forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree_Iterative_InOrder_Traversal.py
72 lines (63 loc) · 2.06 KB
/
Tree_Iterative_InOrder_Traversal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# InOrder tree traversal using python3 (Iterative)
class node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
# creation of tree.
def createTree(self, NodesArray):
queue = []
self.root = node(int(NodesArray.pop(0)))
queue.append(self.root)
size = len(queue)
while NodesArray:
while size:
root = queue.pop(0)
if root:
data = NodesArray.pop(0)
if data == 'null':
root.left = None
else:
root.left = node(int(data))
queue.append(root.left)
data = NodesArray.pop(0)
if data == 'null':
root.right = None
else:
root.right = node(int(data))
queue.append(root.right)
size -= 1
size = len(queue)
# Iterative function to perform in-order traversal of the tree
def inorderIterative(self, root):
stack = []
curr = root
while stack or curr:
# if current node is not null, push it to the stack
if curr:
stack.append(curr)
curr = curr.left
# else if current node is null, we pop an element from the stack,
# print it and finally set current node to its right child
else:
curr = stack.pop()
print(curr.data, end=' ')
curr = curr.right
print("Enter the input:- root.val root->left root->right(enter null if empty)")
NodesArray = list(input().split(' '))
InOrdertree = Tree()
InOrdertree.createTree(NodesArray)
InOrdertree.inorderIterative(InOrdertree.root)
'''
Input-format should be like this :: 10 20 30 40 50 null null
10
/ \
20 30
/ \ / \
40 50 - -
input :: 10 20 30 40 50 null null
output :: 40 20 50 10 30
'''