-
Notifications
You must be signed in to change notification settings - Fork 40
/
tree_preorder_traversal_iterative.py
74 lines (62 loc) · 1.58 KB
/
tree_preorder_traversal_iterative.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
73
74
#!/usr/bin/python
# Date: 2018-11-24
#
# Description:
# Write an iterative program to do preorder traversal of binary tree.
#
# Approach:
# Push root to stack and run loop until stack is not empty:
# - Pop last node from stack and print it
# - If current has right node, push it
# - If current has left node, push it
#
# Reference:
# https://www.geeksforgeeks.org/iterative-preorder-traversal/
#
# Complexity:
# O(N) Time and Space
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def preorder(root):
if not root:
return None
stack = [root]
while stack:
current = stack.pop()
print(current.data, end=' ') # print current node, then traverse lower tree
# In preorder sequence is root(printed above), left then right so we push
# right first then left as stack is LIFO
if current.right:
stack.append(current.right)
if current.left:
stack.append(current.left)
print()
def preorder_simple(root):
# node > left > right
stack = []
node = root
while True:
while node:
stack.append(node)
print(node.data, end=' ')
node = node.left
if not stack:
break
node = stack.pop()
node = node.right
print()
def main():
root = Node(10)
root.left = Node(5)
root.left.left = Node(3)
root.left.right = Node(8)
root.right = Node(15)
root.right.left = Node(12)
root.right.right = Node(18)
preorder(root) # 10 5 3 8 15 12 18
preorder_simple(root) # 10 5 3 8 15 12 18
if __name__ == '__main__':
main()