我如何基于String的对象键实现面向对象的二进制搜索树

时间:2019-07-14 04:41:18

标签: java

我正在尝试根据其名称在Binary Search Tree中查找特定的Pokemon,我的inOrder方法可以按字母顺序对Pokemon进行排序。当我使用相同的逻辑比较我正在寻找的神奇宝贝和树中的神奇宝贝时,它找不到它,而且我也不知道如何解决它。

我尝试使用基于Strings的compareTo方法来确定两个比较对象的名称是否相似,但这可能也存在一些缺陷。

   class PokemonBST { 
        int comparisonCount = 0;


        class Node { 
            // int key;
            Pokemon key; 
            Node left, right; 

            //public Node(int item) { 
            public Node(Pokemon item) { 
                key = item; 
                left = right = null; 
            } 
        } 

        // Root of BST 
        Node root; 

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

        public Pokemon findPokemon(String name) {

            comparisonCount = 0;

            try {
                comparisonCount++;
                Pokemon temp = search(root, new Pokemon(name, 0, 0)).key;

                System.out.println("Comparisons made: " + comparisonCount);
                return temp;
            } catch (NullPointerException e) {

                System.out.println("Pokemon not found!");
                System.out.println("Comparisons made: " + comparisonCount);
                return null;
            }

        }


        public Node search(Node root, Pokemon key) 
        { 
            // Base Cases: root is null or key is present at root 
            if (root==null || root.key.getName()==key.getName()) 
                return root; 

            // val is greater than root's key 
            if (key.getName().compareTo(root.key.getName()) > 0) 
                return search(root.left, key); 

            // val is less than root's key 
            return search(root.right, key); 
        }
void insert(Pokemon key) { 
        root = insertRec(root, key); 
    } 

    /* A recursive function to insert a new key in BST */
    // TODO: What changes need to be made to work with Pokemon instead of int?
    Node insertRec(Node root, Pokemon key) { 
        /* If the tree is empty, return a new node */
        if (root == null) { 
            root = new Node(key); 
            return root; 
        } 

        /* Otherwise, recur down the tree */
        if (key.getName().compareTo(root.key.getName()) < 0) 
            root.left = insertRec(root.left, key); 
        else if (key.getName().compareTo(root.key.getName()) > 0) 
            root.right = insertRec(root.right, key); 

        /* return the (unchanged) node pointer */
        return root; 
    }

    // This method mainly calls InorderRec() 
    void inorder() { 
        inorderRec(root); 
    } 



    // A utility function to do inorder traversal of BST 
    void inorderRec(Node root) { 
        if (root != null) { 
            inorderRec(root.left); 
            System.out.println(root.key); 
            inorderRec(root.right); 
        } 
    } 

} 

我的驱动程序以测试BST:

public class PokemonBSTDriver {
    static PokemonBST myPokemonTree = new PokemonBST();
    public static void main(String[] args) { 
        //TODO: Add code in the main method to perform desired tests
        readPokemonCSV();
        myPokemonTree.inorder();
        Pokemon found = myPokemonTree.findPokemon("Zubat");
        System.out.println(found);
} 

static void readPokemonCSV() {
    BufferedReader br = null;
    int pokemonCount = 0;
    try
    {
        br = new BufferedReader(new FileReader("pokemon.csv"));


        String line = "";
        br.readLine();
        while ((line = br.readLine()) != null) 
        {
            String[] pokemonDetails = line.split(",");

            if(pokemonDetails.length > 0 )
            {
                //Create a temporary pokemon
                Pokemon tempPokemon = new Pokemon();

                tempPokemon.setName(pokemonDetails[1]);
                tempPokemon.setSpeed(Integer.valueOf(pokemonDetails[10]));
                tempPokemon.setTotal(Integer.valueOf(pokemonDetails[4]));

                // Now we use the insert method in the BST to add in our pokemon
                myPokemonTree.insert(tempPokemon);
            }
        }
    }
    catch(Exception ee)
    {
        ee.printStackTrace();
    }
    finally
    {
        try
        {
            br.close();
        }
        catch(IOException ie)
        {
            System.out.println("Error occured while closing the BufferedReader");
            ie.printStackTrace();
        }
    }
    // End of code adapted from Example 1. Using Buffered Reader and String.split() from https://www.javainterviewpoint.com/how-to-read-and-parse-csv-file-in-java/

 }
}

我从.csv文件中收到了按字母顺序添加的所有口袋妖怪的有序树,表明它可以确定字符串的字符,但是无法“查找”特定的口袋妖怪类型。

public int compareTo(Pokemon pokemon) {

    int pokeKey = pokemon.getName().length();
    int key = this.name.length();

    if (pokeKey > key) {
        return 1;
    }
    else if (pokeKey < key) {
        return -1;
    }
    else {
        return this.name.compareTo(pokemon.getName());
    }


}

2 个答案:

答案 0 :(得分:1)

使用equals()代替==``if (root==null || root.key.getName().equals(key.getName()) )

答案 1 :(得分:0)

在您的搜索方法中,root.key.getName()==key.getName()正在检查两个字符串变量是否指向同一对象。但是您需要的是逐个字符地比较两个字符串。因此,必须改为使用equals()方法。将比较项更改为  root.key.getName().equals(key.getName())。希望它可以解决您的问题!