
Visit all the nodes of a Binary tree together to perform an operation is called Binary tree traversal.
All the nodes of the tree are connected via links (edges) and it always starts from the head(root) node and we cannot randomly access a node in a tree
Read Copy : What is Binary Tree?
We traverse a tree to find or search a given key(Item) in the tree or to show all the values it contains. A binary tree can be traverse in 3 types.
In-Order Traversal
In the In-order Traversal, the first Left sub-tree is accessed and then the Root Node is accessed and the Right Sub-tree is accessed/visited in the last. Every node may represent a sub-tree itself.
Now we can understand by its example: -
The output of the image is: -
4, 2, 6, 5, 8, 7, 1, 3, 10, 9
Pre-Order Traversal
In the pre-order traversal, first, the Root Node is visited, then the left subtree is visited, and then the right subtree is visited.
The output of the image is: -
1, 2, 4, 5, 6, 7, 8, 3, 9, 10
Post-Order Traversal
In the post-order traversal, first, the left subtree is visited, then the right subtree is visited, and then the last root node is visited.
The output of the image is: -
4, 6, 8, 7, 5, 2, 10, 9, 3, 1