QWE
QWE

Reputation: 45

Implementation of BInary Tree in java

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

Upvotes: 0

Views: 686

Answers (2)

Soda
Soda

Reputation: 1

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;
    }
}

Upvotes: 0

Siva Kumar
Siva Kumar

Reputation: 2006

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

Upvotes: 1

Related Questions