-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDFS.py
More file actions
28 lines (22 loc) · 723 Bytes
/
DFS.py
File metadata and controls
28 lines (22 loc) · 723 Bytes
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
class Node:
def __init__(self, item):
self.left = None
self.right = None
self.val = item
def IterativePreOrder(root):
#### for iterative port order just reverse the output use python reverse() ######
stack, output = [], []
stack.append(root)
while len(stack) > 0 and root is not None:
node = stack.pop()
output.append(node.val)
if node.right: stack.append(node.right)
if node.left: stack.append(node.left)
return output
if __name__ == '__main__':
root = Node(1)
root.left = Node(3)
root.right = Node(4)
root.left.left = Node(6)
root.left.right = Node(8)
print(IterativePreOrder(root))