Postorder Tree Traversal (DFS) in java

Posted on Updated on

In our previous post we had discussed about different approaches of implementing Preorder and Inorder tree traversal. In this article we shall discuss steps and different ways of implementing Postorder tree traversal.

There are different ways to traversal a tree in DFS such as:

  1. Preorder
  2. Inorder
  3. Postorder

Here in this article, we shall discuss steps and different approach of implementing Postorder tree traversal.

Steps for Postorder Tree Traversal are :

1) Traverse the left subtree, i.e., call Postorder(left-subtree)
2) Traverse the right subtree, i.e., call Postorder(right-subtree)
3) Visit the root.

Postorder Traversal of above tree is 70, 40, 50, 20, 60, 30, 10

Time Complexity: O(n)

There are two ways to implement Postorder Tree Traversal.

1) Recursive
2) Iterative

Recursive solution for Postorder Tree Traversal :

Recursive solution for Postorder Traversal is similar to the steps we had discussed above. Algorithm for recursive solution is

Code for recursive solution

Output

Iterative solution for Postorder Traversal

To implement iterative solution for Postorder Traversal, we will be using Stack data structure. Algorithm for iterative solution is

Code for iterative solution

Output

Download code for Postorder Tree Traversal

PostorderTraversal

Stay tuned for more updates and tutorials !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.