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;
    }
}
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();
t.add(3);
t.add(1);
t.add(4);
t.add(2);
t.add(5);


… to produce the same tree structure.



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.