In the previous tutorial, we have seen inorder traversal of a
binary tree with the help of recursion. Now, in this tutorial we will see
Postorder traversal of a binary tree. In this, firstly, left of the tree is
visited right of tree is visited same and at last root is visited and printed same
applies for subtree. Postorder traversal is also DFS(depth-first-search)algorithm
to traverse the whole tree.
Postorder Traversal: Left Right Root.
Let us take an example.
The Postorder Traversal of above given Binary Tree will be: 6, 7, 5, 20, 30, 10, 2
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
- Then recur to the right subtree using node.right
- Print the node value The same process gets repeated until whole tree is traversed.
Algorithm:
- if (node == null) return
- visit the left subtree.
- visit the right subtree.
- print the node.
Recursive code of Postorder Traversal is implemented below:
Output:
Postorder Traversal is: 6 7 5 20 30 10 2
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.