In the previous tutorial, we have seen preorder traversal of a
binary tree with the help of recursion. Now, in this tutorial we will see
inorder traversal of a binary tree. In this, firstly, left of the tree is
visited then root is printed and then right of tree is visited same
applies for subtree. Inorder traversal also uses DFS(depth-first-search) approach
to traverse the whole tree.
Inorder Traversal: Left Root Right.
Let us take an example.
The Inorder Traversal of above given Binary Tree will be: 6, 5, 7, 2, 20, 10, 30
Explanation:
- If we encounter any node which is null we will return back (this will be the base condition)
- Recur to the left subtree using node.left
- Print the node value
- Then recur to the right subtree using node.right The same process gets repeated until whole tree is traversed.
Algorithm:
- if (node == null) return
- visit the left subtree.
- print the node.
- visit the right subtree.
Recursive code of Inorder Traversal is implemented below:
Output:
Inorder Traversal is: 6 5 7 2 20 10 30
Complexity Analysis:
Time Complexity: O(n), where n is number of nodes in tree. This is because, we are traversing the each node of tree at once.
Space Complexity: We have not used any extra space for storing the nodes values, so O(1) can be considered as space complexity.