BST中的NullPointerException

时间:2016-05-03 12:38:41

标签: java nullpointerexception binary-search-tree

我试图编写一个函数来查找二叉搜索树中的键,但由于某些原因,每次键都不存在时,它会返回NullPointerException而不是返回null。这个功能似乎微不足道 - 任何想法?

public class findFirstKey {

    static Node1 binSearch(Node1 root, int value){

        Node1 tempNode = root;

        while(tempNode!=null){  //  check while condition

            if(tempNode.getData()==value){
                return tempNode;
            }

            else if(value<tempNode.getData()){
                tempNode=tempNode.getLeft();
            }

            else if(value>tempNode.getData()){
                tempNode = tempNode.getRight();
            }

        }
        return null;
    }




    public static void main(String[] args) {

        //  Tree 1. page 258

        Node1 root = new Node1(19);
        Node1 seven = new Node1(7);
        Node1 three = new Node1(3);
        Node1 two = new Node1(2);
        Node1 five = new Node1(5);
        Node1 eleven = new Node1(11);
        Node1 seventeen = new Node1(17);

        Node1 thirteen = new Node1(13);     //  CHANGE THIS TO 9, IT STILL COMES OUT TRUE
        Node1 fortythree = new Node1(43);
        Node1 twentythree = new Node1(23);
        Node1 thirtyseven = new Node1(37);
        Node1 twentynine = new Node1(29);

        Node1 thirtyone = new Node1(31);
        Node1 fortyone = new Node1(41);
        Node1 fortyseven = new Node1(47);
        Node1 fiftythree = new Node1(53);


        root.setLeft(seven);
        seven.setLeft(three);
        three.setLeft(two);
        three.setRight(five);
        seven.setRight(eleven);
        eleven.setRight(seventeen);
        seventeen.setLeft(thirteen);
        root.setRight(fortythree);
        fortythree.setLeft(twentythree);
        twentythree.setRight(thirtyseven);
        thirtyseven.setLeft(twentynine);
        twentynine.setRight(thirtyone);
        thirtyseven.setRight(fortyone);
        fortythree.setRight(fortyseven);
        fortyseven.setRight(fiftythree);

        System.out.println(binSearch(root, 14).getData());

    }

    static class Node1{

        private int data;
        private Node1 left;
        private Node1 right;


        Node1(int data){

            this.data=data;
            this.left=null;
            this.right=null;
        }


        void setLeft(Node1 left){
            this.left = left;
        }

        void setRight(Node1 right){
            this.right = right;
        }

        int getData(){  
            return this.data;
        }

        Node1 getLeft(){
            return this.left;
        }

        Node1 getRight(){
            return this.right;
        }

    }
}

1 个答案:

答案 0 :(得分:0)

您无法在null对象上调用getData()。 像这样添加一个支票:

Node1 target = binSearch(root, 14);
if(target != null)
    System.out.println(target.getData());
else{
    //do or print something else...
}