Write a Java Program to Perform the inorder tree traversal

Inorder traversal is a popular method of traversing a binary tree in which we visit the left subtree first, then the current node, and finally the right subtree.

In this tutorial, we will discuss how to perform the inorder tree traversal in Java using a recursive approach.


First, we need to define the structure of the binary tree.

In Java, we can do this by creating a class for the binary tree node that contains a left and right child node pointer and the data value stored in the node.

Here’s how we can define the TreeNode class in Java:

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}

Next, we can define the recursive function for inorder traversal.

The function takes in a TreeNode pointer as input and recursively traverses the left subtree, then the current node, and finally the right subtree.

Here’s how we can define the function in Java:

void inorderTraversal(TreeNode root) {
    if (root == null) {
        return;
    }
    inorderTraversal(root.left);
    System.out.print(root.val + " ");
    inorderTraversal(root.right);
}

In the above code, we first check if the root node is null.

If it is, we return immediately.

Otherwise, we recursively call the inorderTraversal function on the left child node of the root, print the value stored in the current node, and then recursively call the function on the right child node of the root.

To test our inorder traversal function, we can create a simple binary tree with the following code:

TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);

This creates a binary tree with the following structure:

    1
     / \
    2   3
   / \
  4   5

Finally, we can call our inorder traversal function on the root node of the tree as follows:

inorderTraversal(root);

This should output the following sequence of values:

4 2 5 1 3

In conclusion, we have discussed how to perform the inorder tree traversal in Java using a recursive approach.

By following the steps outlined above, you should be able to implement the inorder traversal algorithm in your own Java programs.