Hello to everyone.

I'm presently working in Java on building a preorder traversal for a binary tree and would appreciate any advice. I discovered this useful post about preorder traversal on a blog, but I'm having difficulties applying the principles to my own code.

Could you possibly help me translate the principles in this paper into Java code? I want to make sure I understand the algorithm and have a workable implementation.

Here's what I've tried so far, but I'm not sure if it's correct:

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
 
    TreeNode(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
    }
}
 
public class PreorderTraversal {
    public void preorder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preorder(root.left);
        preorder(root.right);
    }
 
    public static void main(String[] args) {
        // Create a sample binary tree
        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);
 
        PreorderTraversal traversal = new PreorderTraversal();
        System.out.println("Preorder Traversal:");
        traversal.preorder(root);
    }
}

Is this the correct way to implement a preorder traversal in Java? Any suggestions or improvements would be greatly appreciated.

Thank you in advance for your help!