How does Inorder Traversal of Binary Tree work?
Consider the following tree:
If we perform an inorder traversal in this binary tree, then the traversal will be as follows:
Step 1: The traversal will go from 1 to its left subtree i.e., 2, then from 2 to its left subtree root, i.e., 4. Now 4 has no left subtree, so it will be visited. It also does not have any right subtree. So no more traversal from 4
Step 2: As the left subtree of 2 is visited completely, now it read data of node 2 before moving to its right subtree.
Step 3: Now the right subtree of 2 will be traversed i.e., move to node 5. For node 5 there is no left subtree, so it gets visited and after that, the traversal comes back because there is no right subtree of node 5.
Step 4: As the left subtree of node 1 is, the root itself, i.e., node 1 will be visited.
Step 5: Left subtree of node 1 and the node itself is visited. So now the right subtree of 1 will be traversed i.e., move to node 3. As node 3 has no left subtree so it gets visited.
Step 6: The left subtree of node 3 and the node itself is visited. So traverse to the right subtree and visit node 6. Now the traversal ends as all the nodes are traversed.
So the order of traversal of nodes is 4 -> 2 -> 5 -> 1 -> 3 -> 6.
Inorder Traversal of Binary Tree
Inorder traversal is defined as a type of tree traversal technique which follows the Left-Root-Right pattern, such that:
- The left subtree is traversed first
- Then the root node for that subtree is traversed
- Finally, the right subtree is traversed
Contact Us