-
Notifications
You must be signed in to change notification settings - Fork 591
/
P64_DepthFirstTraversal.py
82 lines (67 loc) · 1.9 KB
/
P64_DepthFirstTraversal.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
75
76
77
78
79
80
81
82
# Author: OMKAR PATHAK
# Depth first search is performed in three ways:
# Inorder
# Preorder
# Postorder
class Node(object):
def __init__(self, data = None):
self.left = None
self.right = None
self.data = data
# for setting left node
def setLeft(self, node):
self.left = node
# for setting right node
def setRight(self, node):
self.right = node
# for getting the left node
def getLeft(self):
return self.left
# for getting right node
def getRight(self):
return self.right
# for setting data of a node
def setData(self, data):
self.data = data
# for getting data of a node
def getData(self):
return self.data
# in this we traverse first to the leftmost node, then print its data and then traverse for rightmost node
def inorder(Tree):
if Tree:
inorder(Tree.getLeft())
print(Tree.getData(), end = ' ')
inorder(Tree.getRight())
return
# in this we first print the root node and then traverse towards leftmost node and then to the rightmost node
def preorder(Tree):
if Tree:
print(Tree.getData(), end = ' ')
preorder(Tree.getLeft())
preorder(Tree.getRight())
return
# in this we first traverse to the leftmost node and then to the rightmost node and then print the data
def postorder(Tree):
if Tree:
postorder(Tree.getLeft())
postorder(Tree.getRight())
print(Tree.getData(), end = ' ')
return
if __name__ == '__main__':
root = Node(1)
root.setLeft(Node(2))
root.setRight(Node(3))
root.left.setLeft(Node(4))
print('Inorder Traversal:')
inorder(root)
print('\nPreorder Traversal:')
preorder(root)
print('\nPostorder Traversal:')
postorder(root)
# OUTPUT:
# Inorder Traversal:
# 4 2 1 3
# Preorder Traversal:
# 1 2 4 3
# Postorder Traversal:
# 4 2 3 1