inorder 2c preorder 2c postorder in python

Solutions on MaxInterview for inorder 2c preorder 2c postorder in python by the best coders in the world

showing results for - "inorder 2c preorder 2c postorder in python"
Constanza
03 Apr 2017
1# Tree traversal in Python
2
3
4class Node:
5    def __init__(self, item):
6        self.left = None
7        self.right = None
8        self.val = item
9
10
11def inorder(root):
12
13    if root:
14        # Traverse left
15        inorder(root.left)
16        # Traverse root
17        print(str(root.val) + "->", end='')
18        # Traverse right
19        inorder(root.right)
20
21
22def postorder(root):
23
24    if root:
25        # Traverse left
26        postorder(root.left)
27        # Traverse right
28        postorder(root.right)
29        # Traverse root
30        print(str(root.val) + "->", end='')
31
32
33def preorder(root):
34
35    if root:
36        # Traverse root
37        print(str(root.val) + "->", end='')
38        # Traverse left
39        preorder(root.left)
40        # Traverse right
41        preorder(root.right)
42
43
44root = Node(1)
45root.left = Node(2)
46root.right = Node(3)
47root.left.left = Node(4)
48root.left.right = Node(5)
49
50print("Inorder traversal ")
51inorder(root)
52
53print("\nPreorder traversal ")
54preorder(root)
55
56print("\nPostorder traversal ")
57postorder(root)Copied