二进制搜索树的代码中有什么错误

时间:2019-07-16 22:17:20

标签: java binary-search-tree

我正在运行代码,但是显示空指针异常,但没有得到这里错过的内容。

该代码位于二元搜索树的插入节点上

代码为:

import java.io.*;
import java.util.*;
class BSTNode
{
    int data;
    BSTNode left;
    BSTNode right;

    BSTNode(int num)
    {
        data=num;
        left=null;
        right=null;
    }

}

上面是制作节点实例的类。

class BST
{
    public static final Scanner sc=new Scanner(System.in);
    public static void main(String ...args)throws IOException
    {

        int num;
        BSTNode head=null;
        while(true)
        {
            int ch=sc.nextInt();
            switch(ch){
            case 1:
                head=insert(head);
                break;


            case 2:
                    inorder(head);
                    break;
                default:
                    System.exit(0);
                }

            }

        }

if语句

中的以下函数中显示异常
public static BSTNode insert(BSTNode head)throws NullPointerException
        {
            System.out.println("Enter  data want to enter");
            //int n=sc.nextInt();
            //while(n--!=0)
            //{
                int num=sc.nextInt();
                BSTNode node=new BSTNode(num);

                if(head==null)
                    head=node;
                else{
                    BSTNode p=head;

                    while(true){
                    if(num<p.data) /***/NullpointerException is showing here(line 59)***
                        {
                            if(p.left!=null)
                            {
                                p.left=node;
                                break;
                            }
                            else
                                p=p.left;       
                        }
                        else{
                            if(p.right!=null)
                            {
                                p.right=node;
                                break;
                            }
                            else
                                p=p.right;
                        }
                    }
                }

            //}
            return head;
        }

输入如下:

    1
    Enter  data want to enter
    3
    1
    Enter  data want to enter
    4
    3
    Exception in thread "main" java.lang.NullPointerException
        at BST.insert(BST.java:59)
        at BST.main(BST.java:31)

0 个答案:

没有答案
相关问题