0

Hi I've implemented a Binary search tree in java. It enters data fine. But it throws a Nullpointer exception when attempt to search. Please point where I am wrong. thanks in Advance...

class Node{
int data;
Node leftChild;
Node rightChild;

}

Follwing is my main method and both search and insert methods..

public class Main {
Node root;

public static void main(String[] args) {
    Main main=new Main();
    main.insert(15);
    main.insert(12);
    main.insert(9);
    main.search(12);

}

void insert(int data){
    Node node=new Node();
    node.data=data;

    if(root==null){
        root=node;
        System.out.println("Root node created: "+root.data);

    }else{
        Node current=root;
        Node parent=null;
        while(true){
            parent=current; 

            if(parent.data>data){
                current=parent.leftChild;
                if(current==null){
                    current=node;
                    System.out.println("Created node: "+current.data);
                    break;
                }

            }else{
                current=parent.rightChild;
                if(current==null){
                    current=node;
                    System.out.println("Created node: "+current.data);
                    break;
                }
            }
            if(current==null){
                break;
            }

        }


    }

}

Node search(int data){
    Node current=root;
    if(root==null){
        System.out.println("Empty binary tree");
    }else{
        while(current.data!=data){
            if(current.data>data){
                current=current.leftChild;
            }else{
                current=current.rightChild;
            }
            if(current==null){
                break;
            }
        }
        System.out.print("Data  item Found :"+current.data);
    }
    return current;

}

}

  • 1
    When you search for 45, which isn't in the tree, you will break out of the loop when `current` is null. Then you are trying to dereference it with `current.data`. You need to make sure `current` is not null first. – gla3dr Mar 03 '16 at 16:57
  • Share stacktrace for easier debugging of the issue. – The Roy Mar 03 '16 at 17:00
  • Yes I have made a mistake their. But as I mentioned above, this does not work for any other existing nodes except root. Search function will detect the root but not any other values that has been inserted using insert function. – Sidath Bhanuka Randeniya Mar 04 '16 at 12:54

0 Answers0