3
\$\begingroup\$

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;
    }
}
\$\endgroup\$
1
\$\begingroup\$

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().

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ I understand your point but I dont want a BST. I just want a binary tree , which does not have a logic for adding nodes. How to do that?? \$\endgroup\$ – VIN Dec 23 '13 at 9:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.