java - 二叉搜索树 字符串搜索

标签 java binary-tree

我有一个程序,我需要在二叉树中搜索特定单词,我为字符串搜索方法编写的代码不起作用。如果有人可以看一下我将不胜感激。

我尝试了一些修改,但仍然不起作用。

public boolean check(BSTNode t,String key){
    if(!t.word.equals(key)){
        check(t.left,key);
        check(t.right,key);
    }
    else{
        return true;
    }
    return false;
}

最佳答案

可以这样写;

public boolean check(BSTNode t,String key) {
    return 
      t.word.equals(key) || check(t.left,key) || check(t.right,key)
}

或者,更详细地说;

public boolean check(BSTNode t,String key) {
    if (t.word.equals(key)) return true;

    if (check(t.left,key)) return true;

    if (check(t.right,key)) return true;

    return false;
}

您不需要大量 else 语句,因为 return 语句会停止函数中的执行。

编辑:

您还必须检查您的 BSTNode 是否不为 null,否则当您到达树的末尾时,您将得到空指针异常。这可以在函数开始时完成,或者在内部递归 check 调用之前完成:

public boolean check(BSTNode t,String key) {

    if (t == null) return false;

    if (t.word.equals(key)) return true;

    if (check(t.left,key)) return true;

    if (check(t.right,key)) return true;

    return false;
}

或者;

public boolean check(BSTNode t,String key) {
    if (t.word.equals(key)) return true;

    if (t.left != null && check(t.left,key)) return true;

    if (t.right != null && check(t.right,key)) return true;

    return false;
}

关于java - 二叉搜索树 字符串搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40937603/

相关文章:

c - 二叉树段错误(核心已转储)

algorithm - "cracking the coding interview(fourth edition)": 4. 7 子树检查

java - 这个函数逐层打印二叉树的时间和空间复杂度

Java接口(interface)MouseMotionListener抽象方法: What's behind the scene?

java - 有没有办法在代码中编写 Eclipse 文件搜索(Ctrl + H)?

java - 列出 Spring Security 中的用户

javascript - 二叉树到 HTML 列表

algorithm - 我试图在时间 O(1) 的二叉搜索树中找到一个键的后继

java - java 质数检查器

java - 从 MySQL 5.5 升级到 5.6 并获取 "SQLException: Connection is closed"