Java program to perform the preorder tree traversal

https:/‮w/‬ww.theitroad.com

Here's a Java program to perform the preorder tree traversal:

class Node {
    int value;
    Node left, right;

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

public class PreorderTraversal {
    Node root;

    PreorderTraversal() {
        root = null;
    }

    void printPreorder(Node node) {
        if (node == null)
            return;

        System.out.print(node.value + " ");

        printPreorder(node.left);

        printPreorder(node.right);
    }

    public static void main(String[] args) {
        PreorderTraversal tree = new PreorderTraversal();
        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);

        System.out.println("Preorder traversal of binary tree is: ");
        tree.printPreorder(tree.root);
    }
}

Explanation:

The program first defines a Node class to represent each node of the binary tree. Each Node object has an int value, a left pointer, and a right pointer.

The PreorderTraversal class is defined to hold the root node of the binary tree and the printPreorder method, which performs the preorder traversal of the tree. The printPreorder method is a recursive function that prints the value of the current node, then calls itself on the left subtree and the right subtree.

In the main method, a new PreorderTraversal object is created, and the root node of the binary tree is set to a new Node object with a value of 1. The left and right child nodes are set to new Node objects with values of 2 and 3, respectively. The left and right child nodes of the left node are set to new Node objects with values of 4 and 5, respectively.

The program then calls the printPreorder method on the root node of the binary tree, and the preorder traversal of the tree is printed to the console.

Note that this program assumes that the binary tree is not empty. If the root node of the tree is null, the printPreorder method will throw a NullPointerException. To handle this case, you could add a null check before calling the printPreorder method in the main method.