-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathIterative_Preorder.py
More file actions
46 lines (38 loc) · 1.2 KB
/
Iterative_Preorder.py
File metadata and controls
46 lines (38 loc) · 1.2 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
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# An iterative process to print preorder traversal of BT
def iterativePreorder(root):
# Base CAse
if root is None:
return
# create an empty stack and push root to it
nodeStack = []
nodeStack.append(root)
# Pop all items one by one. Do following for every popped item
# a) print it
# b) push its right child
# c) push its left child
# Note that right child is pushed first so that left
# is processed first */
while(len(nodeStack) > 0):
# Pop the top item from stack and print it
node = nodeStack.pop()
print (node.data, end=" ")
# Push right and left children of the popped node
# to stack
if node.right is not None:
nodeStack.append(node.right)
if node.left is not None:
nodeStack.append(node.left)
# Driver program to test above function
root = Node(10)
root.left = Node(8)
root.right = Node(2)
root.left.left = Node(3)
root.left.right = Node(5)
root.right.left = Node(2)
iterativePreorder(root)