我的java BST搜索实现有问题吗

我的java BST搜索实现有问题吗,java,algorithm,data-structures,Java,Algorithm,Data Structures,我的bst搜索实现方法有问题,但我不知道为什么在它到达Alice后,我会不断收到错误?不确定是因为找不到它,还是因为我的insert实现不正确?任何帮助都将不胜感激 import static org.junit.Assert.*; import java.util.ArrayList; /** * This is an implementation of a Binary Search Tree (BST). * */ public class BinarySearchTree {

我的bst搜索实现方法有问题,但我不知道为什么在它到达Alice后,我会不断收到错误?不确定是因为找不到它,还是因为我的insert实现不正确?任何帮助都将不胜感激

import static org.junit.Assert.*;

import java.util.ArrayList;

/**
 * This is an implementation of a Binary Search Tree (BST).
 *
 */
public class BinarySearchTree {

    /**
     * Class containing key (name) for a node and right and left children
     */
    class Node {

        private String key;

        public String getKey() {
            return key;
        }

        public void setKey(String key) {
            this.key = key;
        }


        private Node left;

        public Node getLeft() {
            return left;
        }

        public void setLeft(Node left) {
            this.left = left;
        }


        private Node right;

        public Node getRight() {
            return right;
        }

        public void setRight(Node right) {
            this.right = right;
        }

        Node(String key) {
            this.key = key;
            right = null;
            left = null;
        }
    }

    /**
     * The root of the binary search tree (BST)
     */
    Node root;

    // Constructor 
    BinarySearchTree() {  
        root = null;  
    } 

    // Search for a given key in BST
    public Node search(String key) 
    { 
        Node node = null;
        node = searchRecursive(root, key);
        return node;
    }

    // Implement the search recursively in this helper function
    Node searchRecursive(Node root_node, String key) 
    { 
        //Node someNode = new Node(key);

            /**
             * TODO
             * 
             */
            Node someNode = new Node(key);
            if(root_node != null) {
                int comparison = someNode.getKey().compareTo(root_node.getKey());

                if(comparison < 0) {
                    root_node.left = insertRecursive(root_node.left, key);
                }else if(comparison > 0) {
                    root_node.right = insertRecursive(root_node.right, key);
                }
            }else{
                root_node = new Node(key);
            }
            return root_node;





    }

    // Insert a new Node with a key and value in BST
    public void insert(String key) {
        root = insertRecursive(root, key); 
    }

    // Implement the insert recursively in this helper function
    Node insertRecursive(Node root_node, String key) { 
        /**
         * TODO
         * 
         */
        Node someNode = new Node(key);
        if(root_node != null) {
        int comparison = someNode.getKey().compareTo(root_node.getKey());



        if(root_node == null) {
            root_node = new Node(key);
            return root_node;
        }

        if(comparison < 0) {
            root_node.left = insertRecursive(root_node.getLeft(), key);
        }else if(comparison > 0) {
            root_node.right = insertRecursive(root_node.getLeft(), key);
        }

        }
        return root_node;



    } 


    // A recursive inorder traversal of the BST 
    void inorder(Node root, ArrayList<String> strList) { 
        if (root != null) { 
            inorder(root.getLeft(), strList); 
            System.out.println(root.getKey()); 
            strList.add(root.getKey());
            inorder(root.getRight(), strList); 
        }
    }



    public static void main(String[] args) { 

        //For runtime computations
        long startTime, endTime;
        double duration = 0;


        startTime = System.currentTimeMillis();
        BinarySearchTree bst = new BinarySearchTree(); 
        /**
         * TODO:
         * Read in the names from the names.txt file, and
         * Insert all the names in the BST by calling:
         *  insert(name)
         */
        bst.insert("alice");
        bst.insert("zoe");
        bst.insert("alex");

        endTime = System.currentTimeMillis();
        duration += ((double) (endTime - startTime));
        System.out.println("BST insertion runtime is " + duration);

        /**
         * So an inorder traversal of the tree, ensure the result is 
         * order lexicographically
         */
        ArrayList<String> strList = new ArrayList<String>();
        bst.inorder(bst.root, strList);
        //Ensure the inorder traversal gives a 
        //lexicographic ordering of the names
        for (int i = 1; i < strList.size(); i++) {
            assertTrue(strList.get(i-1).compareTo(strList.get(i)) <= 0  );
        }

        /**
         * Verify that search returns the correct result
         */
        startTime = System.currentTimeMillis();
        Node n = bst.search("aaaa");
        assertEquals(n, null);
        endTime = System.currentTimeMillis();
        duration = ((double) (endTime - startTime));
        System.out.println("BST search runtime for aaaa is " + duration);


        startTime = System.currentTimeMillis();
        n = bst.search("alice");
        assertEquals(n.getKey(), "alice");
        endTime = System.currentTimeMillis();
        duration = ((double) (endTime - startTime));
        System.out.println("BST search runtime for alice is " + duration);


        startTime = System.currentTimeMillis();
        n = bst.search("zoe");
        assertEquals(n.getKey(), "zoe");
        endTime = System.currentTimeMillis();
        duration = ((double) (endTime - startTime));
        System.out.println("BST search runtime for zoe is " + duration);

    }
}
import static org.junit.Assert.*;
导入java.util.ArrayList;
/**
*这是一个二进制搜索树(BST)的实现。
*
*/
公共类二进制搜索树{
/**
*类,该类包含节点的键(名称)以及左右子级
*/
类节点{
私钥;
公共字符串getKey(){
返回键;
}
公共无效设置键(字符串键){
this.key=key;
}
私有节点左;
公共节点getLeft(){
左转;
}
公共void setLeft(节点左侧){
this.left=左;
}
私有节点权;
公共节点getRight(){
返还权;
}
公共无效设置权限(节点权限){
这个。右=右;
}
节点(字符串键){
this.key=key;
右=空;
左=空;
}
}
/**
*二叉搜索树(BST)的根
*/
节根;
//建造师
BinarySearchTree(){
root=null;
} 
//在BST中搜索给定的密钥
公共节点搜索(字符串键)
{ 
Node=null;
node=searchRecursive(根,键);
返回节点;
}
//在这个helper函数中递归地实现搜索
节点搜索递归(节点根节点,字符串键)
{ 
//Node someNode=新节点(键);
/**
*待办事项
* 
*/
Node someNode=新节点(键);
if(根节点!=null){
int comparison=someNode.getKey().comparieto(root_node.getKey());
如果(比较<0){
root\u node.left=insertRecursive(root\u node.left,键);
}否则如果(比较>0){
root\u node.right=insertRecursive(root\u node.right,键);
}
}否则{
根节点=新节点(键);
}
返回根节点;
}
//在BST中插入具有键和值的新节点
公共无效插入(字符串键){
root=insertRecursive(根,键);
}
//在这个helper函数中递归地实现insert
节点插入递归(节点根节点,字符串键){
/**
*待办事项
* 
*/
Node someNode=新节点(键);
if(根节点!=null){
int comparison=someNode.getKey().comparieto(root_node.getKey());
if(根节点==null){
根节点=新节点(键);
返回根节点;
}
如果(比较<0){
root\u node.left=insertRecursive(root\u node.getLeft(),key);
}否则如果(比较>0){
root\u node.right=insertRecursive(root\u node.getLeft(),key);
}
}
返回根节点;
} 
//BST的递归有序遍历
void顺序(节点根,ArrayList strList){
如果(根!=null){
顺序(root.getLeft(),strList);
System.out.println(root.getKey());
添加(root.getKey());
顺序(root.getRight(),strList);
}
}
公共静态void main(字符串[]args){
//用于运行时计算
漫长的开始时间,漫长的结束时间;
双倍持续时间=0;
startTime=System.currentTimeMillis();
BinarySearchTree bst=新的BinarySearchTree();
/**
*待办事项:
*从names.txt文件中读取名称,然后
*通过调用以下命令在BST中插入所有名称:
*插入(姓名)
*/
bst.insert(“alice”);
bst.insert(“zoe”);
bst.insert(“alex”);
endTime=System.currentTimeMillis();
持续时间+=((双倍)(结束时间-开始时间));
System.out.println(“BST插入运行时为”+持续时间);
/**
*因此,按顺序遍历树,确保结果是正确的
*按字典顺序排列
*/
ArrayList strList=新的ArrayList();
bst.inoorder(bst.root,strList);
//确保按序遍历提供了一个
//名称的词典排序
对于(int i=1;iassertTrue(strList.get(i-1).compareTo(strList.get(i))当root为null时,我认为在
insertRecursive
实现中大括号的位置不正确

改变

Node insertRecursive(Node root_node, String key) { 
    /**
     * TODO
     * 
     */
    Node someNode = new Node(key);
    if(root_node != null) {
    int comparison = someNode.getKey().compareTo(root_node.getKey());



    if(root_node == null) {
        root_node = new Node(key);
        return root_node;
    }

    if(comparison < 0) {
        root_node.left = insertRecursive(root_node.left, key);
    }else if(comparison > 0) {
        root_node.right = insertRecursive(root_node.right, key);
    }

    }
    return root_node;
}
在这里,如果
大于当前节点的键,则将
向左移动
,但您应该向右移动
,并执行以下行。因此,将方法实现更改为

Node searchRecursive(Node root_node, String key) 
{ 
    //Node someNode = new Node(key);

        /**
         * TODO
         * 
         */

     //Node someNode = new Node(key);
    if(root_node == null || root_node.key.equals(key)) {
        return root_node;
    }

    if(key.compareTo(root_node.key) > 0) {
        return searchRecursive(root_node.right, key);
    }

    return searchRecursive(root_node.left, key);   
}
完整工作演示:

更新:

正如@Maurice Perry在评论中提到的,您不需要创建一个新节点来比较要添加到当前节点的密钥

您可以从
insertRecursive
方法中完全删除这一行

Node someNode = new Node(key);
改变

int comparison = someNode.getKey().compareTo(root_node.getKey());


不确定这是否是问题所在。这是我在控制台上得到的结果。BST插入运行时是0.0 BST搜索运行时,aaaa是线程“main”java.lang.NullPointerException中的6.0异常,位于a5.BinarySearchTree.main(BinarySearchTree.java:195)@DaGuyWhoCodes你能通过一些链接分享你的全部代码吗?@DaGuyWhoCodes我看到的一个问题是你必须把
insertRecursive
code放入
searchRecursive
方法中。谢谢你的帮助。你能再解释一下吗?你的意思是我应该在insertRecursive方法中调用searchRecursive吗?还是d你的意思是我应该把我的搜索递归代码的一部分放在insert中
Node someNode = new Node(key);
int comparison = someNode.getKey().compareTo(root_node.getKey());
int comparison = key.compareTo(root_node.getKey());