Non-Arg constructor Java

376 views java
6

I am calling a constructor in a method to insert new nodes.While I am adding new node default constructor is creating new node with default values . I want to just insert values using insert method as in below code . Is there any way I may avoid first node being default.

class Node {
    Node right, left;
    int data = 0;
    Node(int data) {
        this.data = data;
    }
    public void insert(int value) {
        if (value <= data) {
            if (left == null) {
                left = new Node(value);
            } else {
                left.insert(value);
            }
        } else {
            if (right == null) {
                right = new Node(value);
            } else {
                right.insert(value);
            }
        }
    }
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Node new_node=new Node();//creating first node with 0 value
        new_node.insert(5);
        new_node.insert(4);
        new_node.insert(9);
        new_node.insert(23);
        new_node.insert(70);
        new_node.display();
    }
}

answered question
Add a Comment

1 Answer

10

Like this:

Node new_node = new Node(5); // create 1st node with 1st value

posted this

Please login first before posting an answer.