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

# Pre-order traversal binary tree. Simple Java example.

Boris~November 17, 2020 /Binary Tree

How to implement pre-order traversal? Example of traversing a binary tree in a pre-order way. There are three types of binary tree traversal: pre-order, in-order, post-order. It is a widespread question on any technical interview. So you should know all differences and details. The first and main point is that you need to keep in mind. You will have to use recursion. The second thing you should remember is that you should go through the root node first, then the left branch, and after that right branch in pre-order.

## An important thing you should keep in mind about pre-order traversal.

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

## Code example of the pre-order traversal in a binary tree? The step-by-step solution in Java.

General steps of the traversing are the following:

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

Animated:

Full code:

``````private void preOrderTraversalRecursive(TreeNode node){
//If we face null (end of the "branch") make step back to find other one
if (node == null){
return;
}
//Show in logs data
Log.d("tree", "data -> " + node.data);

//Go on the left side of the tree
preOrderTraversalRecursive(node.left);
//Go on the right side of the tree
preOrderTraversalRecursive(node.right);
}``````

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

Full code and more examples in my facebook group.