-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathIterative_Postorder.py
More file actions
51 lines (41 loc) · 1.1 KB
/
Iterative_Postorder.py
File metadata and controls
51 lines (41 loc) · 1.1 KB
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
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# An iterative function to do postorder
# traversal of a given binary tree
def postOrderIterative(root):
if root is None:
return
# Create two stacks
s1 = []
s2 = []
# Push root to first stack
s1.append(root)
# Run while first stack is not empty
while s1:
# Pop an item from s1 and
# append it to s2
node = s1.pop()
s2.append(node)
# Push left and right children of
# removed item to s1
if node.left:
s1.append(node.left)
if node.right:
s1.append(node.right)
# Print all elements of second stack
while s2:
node = s2.pop()
print node.data,
# Driver program to test above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
postOrderIterative(root)