Post order traversal binary tree. Simple Java example. • IT Blog
IT Blog
Boris IT Expert

# Post order traversal binary tree. Simple Java example.

Boris~November 18, 2020 /Binary Tree

The most simplistic approach to implement post-order traversal. The design of traversing a binary tree in an in-order way. There are three kinds of binary tree traversal: post-order, in-order, pre-order. It is a typical task in any professional interview. Therefore you should learn all variations and details. The initial and primary fact is that you need to keep in mind. You will utilize recursion. The other point you should get is that you should run through the right side first, then the root node, and after that left part.

## An important thing you should remember.

While we are working on recursion, we have to remember about the calls stack. It determines that you should know how the program is running the code during recursion.

## Code example of the post-order traversal in a binary tree? The detailed example in Java.

The main actions of the traversing are the following:

• Check if the node data equals null. We need that check to end the current call and drop it from the stack;
``````//If we face null (end of the "branch") make step back to find other one
if (node == null){
return;
}``````
• Run the recursive call on the left side;
``````        postOrderTraversalRecursive(root.left);
``````
• Run the recursive call on the right side;
``````        postOrderTraversalRecursive(root.right);
``````
• Make any action with the data in the current node. In our sample, we are performing it in the logs;
``````//Show in logs data
Log.d("tree", "data -> " + root.data);``````

Animated:

Full code:

`````` private void postOrderTraversalRecursive(TreeNode root){
//If we face null (end of the "branch") make step back to find other one
if (root == null){
return;
}

postOrderTraversalRecursive(root.left);
postOrderTraversalRecursive(root.right);
//Show in logs data
Log.d("tree", "data -> " + root.data);
}``````

In this article, we figured out how to implement post order traversal in Binary Tree (Java).

Full code and more examples in my facebook group.