-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTree traversal.py
60 lines (43 loc) · 918 Bytes
/
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
49
50
51
52
53
54
55
56
57
58
59
60
'''Trees are non-linear data structure
they can be transversed in many ways:
A.Depth first Traversal
1.Inorder(left root right)
2. Preorder(root left right )
3. Postorder(left right root)
B. Breadth first Traversal:
'''
class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def inorder(root):
if root is not None:
inorder(root.left)
print(root.data)
inorder(root.right)
def postorder(root):
if root is not None:
postorder(root.left)
postorder(root.right)
print(root.data)
def preorder(root):
if root is not None:
print(root.data)
preorder(root.left)
preorder(root.right)
root=Node(1)
a=Node(2)
b=Node(3)
c=Node(4)
d=Node(5)
root.left=a
root.right=b
a.left=c
a.right=d
print("pre")
preorder(root)
print("post")
postorder(root)
print("inorder")
inorder(root)