How can I traverse a binary tree in preorder in Java?
I am learning binary trees in Java using Eclipse, and I want to traverse a binary tree in preorder, but I am not sure if my implementation is correct.
class Node {
int data;
Node left;
Node right;
public Node(int data) {
this.data = data;
left = null;
right = null;
}
}
public class Main {
public static void preorder(Node root) {
if (root != null) {
System.out.println(root.data);
preorder(root.left);
preorder(root.right);
}
}
public static void main(String[] args) {
Node root = new Node(10);
root.left = new Node(5);
root.right = new Node(20);
root.left.left = new Node(3);
preorder(root);
}
}
I want to confirm whether this output actually corresponds to a preorder traversal.
What I Have Tried
I compared the output with examples online.
I reviewed the order of the recursive calls.
I changed the print order and got different results.