Java program to perform the inorder tree traversal

In-order traversal is one of the three depth-first traversal methods for binary trees. In Java, inorder traversal can be implemented recursively using the following algorithm:

refer ‮figi:ot‬tidea.com
class Node {
    int data;
    Node left, right;

    public Node(int data) {
        this.data = data;
        left = right = null;
    }
}

public class BinaryTree {
    Node root;

    public BinaryTree() {
        root = null;
    }

    public void inOrderTraversal(Node node) {
        if (node == null) {
            return;
        }

        inOrderTraversal(node.left);
        System.out.print(node.data + " ");
        inOrderTraversal(node.right);
    }

    public static void main(String[] args) {
        BinaryTree tree = new BinaryTree();

        /* Construct the binary tree */
        tree.root = new Node(1);
        tree.root.left = new Node(2);
        tree.root.right = new Node(3);
        tree.root.left.left = new Node(4);
        tree.root.left.right = new Node(5);

        /* Perform in-order traversal */
        System.out.print("In-order Traversal: ");
        tree.inOrderTraversal(tree.root);
    }
}

In the above example, we define a Node class to represent the nodes of the binary tree. We also define a BinaryTree class with an inOrderTraversal method that performs in-order traversal. The inOrderTraversal method takes a Node parameter and recursively traverses the left subtree, then prints the data of the current node, and finally recursively traverses the right subtree.

In the main method, we create a new binary tree and add some nodes to it. We then call the inOrderTraversal method on the root node of the tree to perform the in-order traversal. The output will be the values of the nodes in the binary tree in sorted order.

Output:

In-order Traversal: 4 2 5 1 3