0

I am trying to implement Binary tree in java and here is my code:

class TestClass {

    public static  void newnode(int a , Node root,){


             root = new  Node(a);
              System.out.println(root.data);   // Printing out 22

                                          }
    public static void main(String args[] ) throws IOException {


      Node root = null;
      newnode(22,root);
      System.out.println(root.data);  // Giving NullPointerException


    }
    }
    class Node{ 
        Node left ;
        Node Right;
        int data ;

        Node(int dataa){

            this.data = dataa;
        }
    }

I could not insert a new node in my tree , the value of root does not changes

When i call newnode function I getting the correct value of my Root Node but in the main function it gives me null point exception

Why the value of root is not updating

1
  • You're more likely to get help if you format your code reasonably. Commented Dec 16, 2014 at 6:41

2 Answers 2

1
class TestClass {

    public static  Node newnode(int a , Node root){
        root = new  Node(a);
        System.out.println(root.data);   // Printing out 22
        return root;
    }
    public static void main(String args[] ) throws IOException {
        Node root = null;
        root = newnode(22,root);
        System.out.println(root.data);  // Giving NullPointerException
    }
}

try this

Sign up to request clarification or add additional context in comments.

Comments

0

You shouldn't design methods with a lot of input parameters, because testing will be more painful. Also, there is no need to pass null to method just to assign an object to it - this is poor design.

import java.io.IOException;

class TestClass {
    // This method is useless, use Factory Design Pattern if you want 
    // to create such solution with multiple variants
    public static Node newNode(int a) {
        return new Node(a);
    }

    public static void main(String args[]) throws IOException {
        Node root = newNode(22);
        System.out.println(root.getData());
    }
}

class Node { 
    private int data;
    private Node left;
    private Node right;

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

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.