Create a program to construct a binary search tree consisting of nodes that each stores
an integer in Java, avoid duplication of values when inserting nodes in the tree. When a new leaf node is created list all the nodes in the path from the newly added leaf node to the root of the tree. It is sufficient to list only the value the node holds since duplication is not permitted. When listing each node also print the next two children in the path from the root to the newly added
leaf node.
For example. Assume a binary search tree is constructed from the values 14, 35, 2, 3,
39, and 27. Now suppose the value 37 is added to the tree. When inserting 37 your program
should print out something similar to the following:
37 -> null -> null
39 -> 37 -> null
35 -> 39 -> 37
14 -> 35 -> 39
Generate random values between zero and twice the number of values to add to the
tree. For example, if you are inserting ten values (not necessarily unique) then the random
values would fall between 0 and 20. Generate random integers to create a tree containing up to
the number of nodes indicated by a command line argument (perhaps less if duplication

please help me out in fulfilling the requirement of the question. asap. i need to generate the random number and insert elements in the tree. thanks.

public class BinarytreeInsert {

    public static void main(String[] args) {
        new BinarytreeInsert().run();

    static class Node {

        Node left;
        Node right;
        int value;

        public Node(int value) {
            this.value = value;

    public void run() {
        Node rootnode = new Node(25);
        System.out.println("Building tree with root value " + rootnode.value);


    public void insert(Node node, int value) {
        if (value < node.value) {
            if (node.left != null) {
                insert(node.left, value);
            } else {
                System.out.println("  Inserted " + value + " to left of Node " + node.value);
                node.left = new Node(value);
        } else if (value > node.value) {
            if (node.right != null) {
                insert(node.right, value);
            } else {
                System.out.println("  Inserted " + value + " to right of Node " + node.value);
                node.right = new Node(value);

Edited by Dani: Formatting fixed

4 Years
Discussion Span
Last Post by ejosiah

Please edit your post and wrap the code in code tags. Use the [code] icon above the input box.

i need to generate the random number

See the Random class for a way to generate random numbers.

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.