java中的二叉搜索树抛出Nullpointer异常

时间:2016-03-03 16:53:39

标签: java binary-search-tree

您好我在java中实现了二进制搜索树。它输入数据很好。但是在尝试搜索时会抛出Nullpointer异常。请指出我错了。在此先感谢...

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

}

Follwing是我的主要方法,也是搜索和插入方法..

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;

}

}

0 个答案:

没有答案