【问题标题】:Binary Search Tree searching in javajava中的二叉搜索树搜索
【发布时间】:2015-03-30 03:23:34
【问题描述】:

我正在尝试制作一个 BST 程序,该程序能够插入给定的数字,然后通过说真或假来告诉用户该数字是否在 BST 中。但是,即使插入了数字,它也总是注册为假。谁能告诉我这里哪里出错了?如果需要,我可以提供其余的类文件。

public class BinarySearchTree implements BST
{
private int n;
private Node r;
private Node l;

public void enter(int num)
{
    Node node = new Node(num);

    if (num < node.getData())
    {
        if (node.getL() != null)
        {
            insert(num);
        }

        else
        {
            node.setL(new Node(num));
        }
    }

    else if (num > node.getData())
    {
        if (node.getR() != null)
        {
            insert(num);
        }

        else
        {
            node.setR(new Node(num));
        }
    }
}

public boolean search (int num)
{
    if (num == this.n)
    {
        return true;
    }

    else if (num > this.n)
    {
        if (r == null)
        {
            return false;
        }

        else
        {
            return true;
        }
    }
    else if (num < this.n)
    {
        if (l == null)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    return false;
}
}

【问题讨论】:

    标签: java search insert binary-search-tree


    【解决方案1】:

            insert(num);
    

    向左和向右,insert() 是否检查它是否必须再次向左或向右?

    node
    

    已使用但未在任何地方声明。

    希望你明白这个想法,发布整个内容。

    另外,当您的问题返回 false 时。您的代码比这更频繁地返回 true (从技术上讲,不应该仅仅因为 num > this.n 而我们得到一个右或左就返回 true)。所以你的第一个问题是你的树的构建,你必须是错误的才能获得错误,一旦你修复它,修复搜索。

    【讨论】:

      【解决方案2】:

      如果这不是作业或类似的东西: 使用实现红黑树的 TreeSet

      Set<Number> numbers = new TreeSet<Number>();
      numbers.add(...);
      
      if (numbers.contains(...)) {
        ...
      }
      

      【讨论】:

        【解决方案3】:
        1. 在 BST 类中,可以将搜索和插入功能与一个根节点一起保留。您在 BST 中也保留了节点内部变量,坦率地说,这很令人困惑。
          2。如果您将空检查添加到您的插入功能,您将不需要另一个输入功能。
          3。此外,您的搜索功能完全错误,因为您只在第一级检查相等性。您必须在左右两侧递归地执行此操作,直到找到密钥或用完节点。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2023-03-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-09
          相关资源
          最近更新 更多