-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtree_traversal.py
48 lines (35 loc) · 1.01 KB
/
tree_traversal.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
# https://www.geeksforgeeks.org/tree-traversals-inorder-preorder-and-postorder/
# explanation: https://youtu.be/xo41NfT8218
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.value = key
def print_preorder(root):
if root:
print(root.value, end=" ")
print_preorder(root.left)
print_preorder(root.right)
def print_in_order(root):
if root:
print_in_order(root.left)
print(root.value, end=" ")
print_in_order(root.right)
def print_post_order(root):
if root:
print_post_order(root.left)
print_post_order(root.right)
print(root.value, end=" ")
if __name__ == "__main__":
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Preorder traversal: ")
print_preorder(root)
print("\nInOrder traversal: ")
print_in_order(root)
print("\nPostOrder traversal: ")
print_post_order(root)
print()