Postorder Traversal in Binary Tree in java

What is Postorder Traversal ?

In postorder traversal , first we traverse the left subtree, then the right subtree and finally the root node.post order traversal is used to get the postfix expression of an expression given. In this article we will see how to perform postorder traversal in java.

Postorder Tree Traversal of a binary tree in Java

Postorder Traversal Example

Steps to find Postorder traversal

    Here are some of the steps to find postorder traversal :
  • Step 1: Print the left most child of left subtree of binary tree i.e 20.
  • Step 2: Now , before printing the root node, move to right sub-tree and print the left child i.e. 40.
  • Step 3: Print 50 which is right child.
  • Step 4: Now, print it’s root node 30.
  • Step 5: At last print the root of the tree i.e. 10.

The printing sequence will be  20,40,50,30,10.

 

Algorithm to find Postorder traversal

Algorihtm postorder(Tree):

  1. Recursively traverse left sub-tree.
  2. Recursively traverse right sub-tree.
  3. Visit root node.

CODE FOR Postorder Traversal of a Binary Tree using Recursion

//Postorder Traversal 
/*Node class with left and right child and current node and key value*/
class Node
{
   Node left ,right;
   int value;
   Node(int value)
   {
       this.value=value;
       left=null;
       right=null;
   }
}
class Postorder
{
   Node root; //root node of the binary tree
   Postorder()
   {
       root=null;
   }  
   /*postorder traversal of binary tree */
   public  void postorder(Node ptr)
   {
       if(ptr==null)
       return ;
       /*first traverse left child*/   
       postorder(ptr.left);
       /*then traverse the right child*/
       postorder(ptr.right);
       /*now print the value of node*/
      System.out.print(ptr.value+" ");
   }
   public static void main(String[] args)
   {
       Postorder t=new Postorder();
       t.root=new Node(10);
       t.root.left=new Node(20);
       t.root.right=new Node(30);
       t.root.right.left=new Node(40);
       t.root.right.right=new Node(50);
       t.postorder(t.root);
   }
}

Output :

20 40 50 30 10

TIME & SPACE Complexity for Postorder Traversal of a Binary Tree

Time Complexity

O(n)

Space Complexity

O(h)