【问题标题】:Binary Search Tree searching a string by letter [closed]二叉搜索树按字母搜索字符串[关闭]
【发布时间】:2018-10-08 11:29:42
【问题描述】:

您好,我是一名新手程序员,试图弄清楚如何仅使用开头的第一个字母在二叉搜索树中搜索字符串,例如,如果只搜索字母“L”,它应该会显示所有以那个字母开头的名字。以下是目前我们如何搜索全名的方法。

public void searchByName() throws IOException//My pride and joy
    {

        String exit=null;//to exit the inner while loop
        Boolean end=false;// exit the outer while loop

        while(end!=true) //search author by first name loop 
        {


            @SuppressWarnings("resource")
            Scanner keyboard = new Scanner(System.in);

            System.out.printf("Please enter the Author's Last and First:(please enter in this format(Johnson, Cevion)\n");
                String name = keyboard.nextLine();

                System.out.println("This is what we found!!\n");

                System.out.println(findFullName(name));


                System.out.printf("Do you want to search again?? Yes or No\n");//search again loop
                exit = keyboard.nextLine();


                while(!exit.equalsIgnoreCase("yes")&&!exit.equalsIgnoreCase("no"))//yes or no only loop
                {
                    System.out.printf("Invaild choice please enter: Yes or No\n");
                    exit = keyboard.nextLine();
                }

                if(exit.equalsIgnoreCase("yes"))
                    end=false;
                if(exit.equalsIgnoreCase("no"))
                    end=true;
        }

    }

【问题讨论】:

  • 您显示的代码实际上并不相关。而且它通常不是 binary 树,因为有超过 2 种类型的字母。例如查看en.wikipedia.org/wiki/Trie 并在互联网上搜索更多内容。您目前缺少您可能在此处提出的问题的详细信息。提示:树通常涉及递归。

标签: java string binary-search-tree letters


【解决方案1】:

二进制尝试不适用于这种搜索,您最好使用hashmap: string -> array

如果您想在树中实现这种行为,您将需要修改(或创建)search method,一旦它找到符合条件的第一个节点,在您的情况下,字符串以“L”开头,它需要返回该节点并从该节点开始遍历树, 您可以通过简单的进出顺序遍历等来完成...并检查所有后续节点是否符合该标准,直到到达叶子节点才会停止,因此会导致查找复杂性,因为 O(N) 基本上遍历所有(子)树..

【讨论】:

    猜你喜欢
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    • 1970-01-01
    相关资源
    最近更新 更多