1# Python program to for tree traversals
2
3# A class that represents an individual node in a
4# Binary Tree
5class Node:
6 def __init__(self,key):
7 self.left = None
8 self.right = None
9 self.val = key
10
11
12# A function to do inorder tree traversal
13def printInorder(root):
14
15 if root:
16
17 # First recur on left child
18 printInorder(root.left)
19
20 # then print the data of node
21 print(root.val),
22
23 # now recur on right child
24 printInorder(root.right)
25
26
27
28# A function to do postorder tree traversal
29def printPostorder(root):
30
31 if root:
32
33 # First recur on left child
34 printPostorder(root.left)
35
36 # the recur on right child
37 printPostorder(root.right)
38
39 # now print the data of node
40 print(root.val),
41
42
43# A function to do preorder tree traversal
44def printPreorder(root):
45
46 if root:
47
48 # First print the data of node
49 print(root.val),
50
51 # Then recur on left child
52 printPreorder(root.left)
53
54 # Finally recur on right child
55 printPreorder(root.right)
56
57
58# Driver code
59root = Node(1)
60root.left = Node(2)
61root.right = Node(3)
62root.left.left = Node(4)
63root.left.right = Node(5)
64print "Preorder traversal of binary tree is"
65printPreorder(root)
66
67print "\nInorder traversal of binary tree is"
68printInorder(root)
69
70print "\nPostorder traversal of binary tree is"
71printPostorder(root)
72
1class Node:
2 def __init__(self,key):
3 self.left = None
4 self.right = None
5 self.val = key
6
7root = Node(1)
8root.left = Node(2);
9root.right = Node(3);
10root.left.left = Node(4);
11