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

# In order traversal binary tree. Simple Java example.

Boris~November 18, 2020 /Binary Tree

The simplest way to implement pre-order traversal. The pattern of traversing a binary tree in an in-order way. There are three varieties of binary tree traversal: in-order, pre-order, post-order. It is a common task in any technical interview. Thus you should understand all variations and details. The primary and central fact is that you need to keep in memory. You will use recursion. The other thing you should get is that you should go through the left side first, then the root node, and after that right branch.

## A critical thing you should keep in mind.

While we are operating recursion, we have to memorize the calls stack. It determines that you should understand how the program is operating the code throughout recursion.

## Code sample of the in-order traversal in a binary tree? The step-by-step explanation in Java.

The main steps of the traversing are the following:

• Verify if the node data matches null. We need that check to stop the current call and eliminate 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;
``       preOrderTraversalRecursive(node.left);``
• Make any manipulation with the data in the current node. In our sample, we are displaying it in the logs;
``````//Show in logs data
Log.d("tree", "data -> " + node.data);``````
• Run the recursive call on the right side;
``````        preOrderTraversalRecursive(node.right);
``````

Animated:

Full code:

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

inOrderTraversalRecursive(root.left);

//Show in logs data
Log.d("tree", "data -> " + root.data);

inOrderTraversalRecursive(root.right);
}
``````

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

Full code and more examples in my facebook group.