Constructing a binary tree in java

I am constructing a binary tree. Let me know if this is a right way to do it. If not please tell me how to?? I could not find a proper link where constructing a general binary tree has been coded. Everywhere BST is coded.

  3
/ \
1   4
/ \
2   5


This is the binary tree which i want to make.I should be able to do all the tree traversals.Simple stuff.

public class Binarytreenode
{
public Binarytreenode left;
public Binarytreenode right;
public int data;

public Binarytreenode(int data)
{
this.data=data;
}

public void printNode()
{
System.out.println(data);
}

public static void main(String ar[])
{
Binarytreenode root = new Binarytreenode(3);
Binarytreenode n1 = new Binarytreenode(1);
Binarytreenode n2 = new Binarytreenode(4);
Binarytreenode n3 = new Binarytreenode(2);
Binarytreenode n4 = new Binarytreenode(5);

root.left = n1;
root.right = n2;
root.right.left = n3;
root.right.right = n4;
}
}


If you just want to be able to construct arbitrary trees, you could introduce some convenience functions:

public static Binarytreenode n(int datum) {
return new Binarytreenode(datum);
}

public static Binarytreenode n(Binarytreenode left, int datum, Binarytreenode right) {
Binarytreenode root = n(datum);
root.left = left;
root.right = right;
return root;
}

public static void main(String[] args) {
Binarytreenode root = n(n(1), 3, n(n(2), 4, n(5)));
}


With the right imagination, you can visualize the tree in main().

Your code does represent the tree that you drew. However, the code doesn't implement the logic for determining where to place nodes within a binary search tree; instead, you hard-coded that logic in your main() function. A useful implementation of Binarytreenode would let you write something like

BinaryTree t = new BinaryTree();

You want to design the code as a class that maintains the tree in a self-consistent state, supporting operations such as .add(int value) and .find(int value). The member fields left, right, and data should generally not be have public access, which would let other code modify the tree in an invalid way. It could be acceptable, however, to let data remain public if you also mark it as final.