forked from priyankchheda/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdepth_first_traversal.py
61 lines (47 loc) · 1.33 KB
/
depth_first_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
49
50
51
52
53
54
55
56
57
58
59
60
61
""" Depth First Traversals of Binary Tree
- Inorder Traversals (left, root, right)
- Preorder Traversals (root, left, right)
- Postorder Traversals (left, righti, root)
"""
class Node:
""" class representing node in binary tree """
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def inorder(root):
""" inorder traversal (left, root, right) """
if root is not None:
inorder(root.left)
print(root.data, end=" ")
inorder(root.right)
def preorder(root):
""" preorder traversal (root, left, right) """
if root is not None:
print(root.data, end=" ")
preorder(root.left)
preorder(root.right)
def postorder(root):
""" postorder traversal (left, right, root) """
if root is not None:
postorder(root.left)
postorder(root.right)
print(root.data, end=" ")
def main():
""" operational function """
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print("Inorder Traversals: ", end="")
inorder(root)
print()
print("Preorder Traversals: ", end="")
preorder(root)
print()
print("Postorder Traversals: ", end="")
postorder(root)
print()
if __name__ == "__main__":
main()