Tree Traversal
Tree Traversal
Traversal is a process to visit all the nodes of a tree and may print their values too
Tree Traversal Algorithms can be classified broadly in the following two categories
by the order in which the nodes are visited:
Depth-First Search (DFS) Algorithm: It starts with the root node and first visits all
nodes of one branch as deep as possible of the chosen Node and before
backtracking, it visits all other branches in a similar fashion. There are three sub-
types under this
Breadth-First Search (BFS) Algorithm: It also starts from the root node and visits
all nodes of current depth before moving to the next depth in the tree.
Tree traversal techniques
Preorder Traversal
Inorder Traversal
Postorder Traversal
Traversal is a process to visit all the nodes of a tree and may print
their values too
20
20,10,25
10 25
20,4 ,25,21,26
20
4 25
21 26
20 Root, Left , Right
4 25
3 5 21 26
25
4
3 5 21 26
20
10,20,25
10 25
20 4,20,21,25,26
4 25
21 26
Inorder
20
25
4
3 5 21 26
3 4 5 20 21 25 26
20, 4, 3, 51, 25, 21, 26,2
4 51
25
3
21 26
2
we visit the left subtree and the right subtree before visiting the
current node in recursion
1. Go to left-subtree
2. Go to right-subtree
3. Visit Node
Left , Right, Root
20
10,25,20
10 25
20 4,21,26,25,20
4 25
21 26
Post-order
Leaf break from left side
20
25
4
3 5 21 26
3 ,5 ,4, 21,26,25,20