File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Tree traversal in Python
2+
3+
4+ class Node:
5+ def __init__(self, item):
6+ self.left = None
7+ self.right = None
8+ self.val = item
9+
10+
11+ def 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+
22+ def 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+
33+ def 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+
44+ root = Node(1)
45+ root.left = Node(2)
46+ root.right = Node(3)
47+ root.left.left = Node(4)
48+ root.left.right = Node(5)
49+
50+ print("Inorder traversal ")
51+ inorder(root)
52+
53+ print("\nPreorder traversal ")
54+ preorder(root)
55+
56+ print("\nPostorder traversal ")
57+ postorder(root)
58+ Previous Tutorial:
59+ Tree Data Structure
60+ Next Tutorial:
61+ Binary Tree
62+ Share on:
63+
64+ Was this article helpful?
65+
You can’t perform that action at this time.
0 commit comments