-
Notifications
You must be signed in to change notification settings - Fork 619
/
Copy pathdfs_iterative.py
72 lines (60 loc) · 1.47 KB
/
dfs_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
class Node():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def inorder(root):
if not root:
return None
stack = []
# Keep adding left until there is none
while True:
if root:
stack.append(root)
root = root.left
else:
if not stack:
break
root = stack.pop()
print(root.val, end=" ")
root = root.right
def postorder(root):
if not root:
return None
stack = []
curr = root
while curr or stack:
if curr:
stack.append(curr)
curr = curr.left
else:
temp = stack[-1].right
if not temp:
temp = stack.pop()
print(temp.val, end=" ")
while stack and temp == stack[-1].right:
temp = stack.pop()
print(temp.val, end=" ")
else:
curr = temp
def preorder(root):
if not root:
return None
stack = [root]
while stack:
root = stack.pop()
print(root.val, end=" ")
if root.right:
stack.append(root.right)
if root.left:
stack.append(root.left)
root = Node(5)
root.left = Node(2)
root.right = Node(7)
root.left.left = Node(1)
root.left.right = Node(3)
root.right.right = Node(8)
root.right.left = Node(6)
#inorder(root)
#preorder(root)
postorder(root)