Post order traversal Algorithms for Binary Tree in Java with example

In the last couple of articles, you have learned about pre-order and in-order tree traversal algorithms in Java, and today, you will learn about the post-order traversal in a binary tree. It is the toughest of all three tree traversal algorithms and programmers generally struggle to implement this when asked in a coding interview. Hence it makes sense to understand and practice this algorithm before going for the interview. The post order traversal is also a depth-first algorithm because you go deep before you visit other nodes on the same level.

In postorder traversal, you first visit the left subtree, then right subtree, and finally you print the value of the node or root. The value of the root is always printed last on post-order traversal. Like many tree algorithms, the easiest way to implement post-order traversal is by using recursion.

In fact, if you know how to write a pre-order using recursion, you can use the same algorithm with a bit of adjustment to implement post-order traversal. Instead of printing the value of the node first, all you need to do is call the recursive method with the left subtree as shown in our example.

Though non-recursive or an iterative version of post-order traversal is a bit difficult and that's why mostly asked during coding interviews, if you remember a simple trick that a stack data structure can convert a recursive algorithm to an iterative one, then you can easily code post-order algorithms as well.

Anyway, that's not the topic of this article, though, here, we'll focus on recursive algorithms and I'll explain iterative algorithms in another article like I have done previously with iterative pre-order and in-order algorithms.

Unlike in-order traversal, which prints all nodes of the binary search tree in sorted order, post-order doesn't provide sorting but it is frequently used while deleting nodes from the binary tree, see a good book or online course on data structure and algorithms like Data Structures and Algorithms: Deep Dive Using Java to learn more about different usage of post-order traversal in Computer Science and programming.





Post-order traversal using Recursion

The recursive algorithm is very easy to understand as it is exactly similar to the recursive preOrder and recursive inOrder traversal. The only different thing is the order in which the left subtree, right subtree, and root are visited or traversed as shown in the following code snippet.

private void postOrder(TreeNode node) {
    if (node == null) {
      return;
    }

    postOrder(node.left);
    postOrder(node.right);
    System.out.printf("%s ", node.data);
  }

You can see that algorithm is exactly similar to the pre-order algorithm, except that the order of traversal to root, left sub-tree, and right subtree is different. In this code, the left subtree is visited. First, the right subtree is visited second, and the node's value is printed third.

If you want to learn more about the recursive post-order traversal algorithm like its real-world examples and complexity assessment, I suggest you take a look at Data Structures, and Algorithms Specialization on Coursera, one of the best data structure and algorithm resources for Java developers as examples are given in Java programming language.

Binary tree post order traversal in Java with example




Java Program to print the binary tree in a post-order traversal

Here is the complete Java program to print all nodes of a binary tree in the post-order traversal. In this part of the tutorial, we are learning the recursive post-order traversal, and next part, I'll show you how to implement a post-order algorithm without recursion, one of the toughest tree traversal algorithms for beginners programmers.

Similar to our earlier examples, I have created a class called BinaryTree to represent a binary tree in Java. This class has a static nested class representing a tree node called TreeNode. This is similar to the Map.Entry class is used to represent an entry in the hash table. The class just keeps the reference to root, and TreeNode takes care of the left and right children.

This class has two methods, postOrder() and postOrder(TreeNode root), the first one is public, and the second one is private. The actual traversing is done in the second method, but since the root is internal to the class and the client doesn't have access to the root, I have created a postOrder() method, which calls the private method. This is a common trick to implement a recursive algorithm.

This also gives you the luxury to change your algorithm without affecting clients. Like tomorrow, we can change the recursive algorithm to an iterative one, and the client will still be calling the post order method without knowing that now the iterative algorithm is in place.

And if you want to learn more about the theory part of the binary tree and other fundamental data structures, then please see Algorithms and Data Structures - Part 1 and 2 courses on Pluralsight. One of the best courses for beginners.

Anyway, here is the binary tree which you need to traverse in the post order; the problem is solved by the following example as well:





Printing nodes of a binary tree in post order

import java.util.Stack;

/*
 * Java Program to traverse a binary tree 
 * using postOrder traversal without recursion. 
 * In postOrder traversal first left subtree is visited, 
 * followed by right subtree
 * and finally data of root or current node is printed.
 * 
 * input:
 *     55
 *    /  \
 *   35   65
 *   / \    \
 *  25  45   75
 *  /  /  \
 * 15 87  98
 * 
 * output: 15 25 45 35 87 98 75 65 55 
 */

public class Main {

  public static void main(String[] args) throws Exception {

    // construct the binary tree given in question
    BinaryTree bt = BinaryTree.create();

    // traversing binary tree using post-order traversal using recursion
    System.out.println("printing nodes of a binary tree on post order in Java");

    bt.postOrder();

  }

}

class BinaryTree {
  static class TreeNode {
    String data;
    TreeNode left, right;

    TreeNode(String value) {
      this.data = value;
      left = right = null;
    }

    boolean isLeaf() {
      return left == null ? right == null : false;
    }

  }

  // root of binary tree
  TreeNode root;

  /**
   * traverse the binary tree on post order traversal algorithm
   */
  public void postOrder() {
    postOrder(root);
  }

  private void postOrder(TreeNode node) {
    if (node == null) {
      return;
    }

    postOrder(node.left);
    postOrder(node.right);
    System.out.printf("%s ", node.data);
  }

  /**
   * Java method to create binary tree with test data
   * 
   * @return a sample binary tree for testing
   */
  public static BinaryTree create() {
    BinaryTree tree = new BinaryTree();
    TreeNode root = new TreeNode("55");
    tree.root = root;
    tree.root.left = new TreeNode("35");
    tree.root.left.left = new TreeNode("25");
    tree.root.left.left.left = new TreeNode("15");

    tree.root.left.right = new TreeNode("45");
    tree.root.right = new TreeNode("65");
    tree.root.right.right = new TreeNode("75");
    tree.root.right.right.left = new TreeNode("87");
    tree.root.right.right.right = new TreeNode("98");

    return tree;
  }

}

Output
printing nodes of a binary tree on post order in Java
15 25 87 98 45 35 75 65 55  


That's all about how to implement post-order traversal in Java. You can use this algorithm to print all nodes of a binary tree in the post order. Remember that in post-order traversal, you first visit the left subtree, followed by the right subtree, and finally, the value of the node or root is printed.

This is also why root is printed at last on post-order traversal. If you want to learn more about post-order traversal or other binary tree algorithms, I suggest exploring the following resources to learn about Data Structures and Algorithms in depth.


Other Binary tree tutorials  in Java you may like to explore
  • Top 5 data structure and algorithm books for coding interviews (list
  • How to implement pre-order traversal in Java? (solution
  • Java Program to traverse a binary tree in pre-order without recursion (program)
  • 20+ binary tree-based coding problems from interviews (questions)
  • How to implement in-order traversal in Java? (solution
  • How to implement in-order traversal in Java without recursion? (solution
  • How to print all leaf nodes of a binary tree in Java? (solution
  • Java Program to print leaf nodes of a binary tree without recursion? (program)
  • 21 string coding interviews with answers (questions)
  • How to traverse a binary tree in pre-order without using recursion? (solution
  • How to print all leaf nodes of a binary tree without recursion in Java? (solution
  • How to implement a linked list using generics in Java? (solution
  • How to reverse a singly linked list in Java? (solution
  • Find the 3rd element from the end of a linked list in Java? (solution)
  • How to find the middle element of a linked list using a single pass? (solution
  • Java program to implement binary search using recursion? (solution
  • How to reverse an array in place in Java? (solution
  • How to print duplicate elements of an array in Java? (solution)

P. S. - If you are looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check these free Data Structure and Algorithms courses from Coursera and Udemy. They all are authored by experts, and it's completely free of cost.

4 comments:

  1. Your tree structure is not drawn correctly in image as well as javadoc, with respect to coding.

    ReplyDelete
    Replies
    1. Yeah, thank for pointing it out, I'll correct it.

      Delete
  2. ya in image of the post order tree is not correct value because 15 and you are write in the answer 55?

    ReplyDelete
    Replies
    1. Yes, I need to update the image, thanks for pointing out.

      Delete

Feel free to comment, ask questions if you have any doubt.