簡體   English   中英

用Java搜索二進制搜索樹

[英]Binary Search Tree searching in java

我試圖制作一個能夠插入給定號碼的BST程序,然后通過說是或否來告訴用戶號碼是否在BST中。 但是,即使插入了數字,它也始終注冊為false。 有人能告訴我我在哪里錯嗎? 如果需要,我可以提供其余的班級文件。

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;
}
}

        insert(num);

無論是在左側還是右側,insert()都會檢查它是否必須再次向左或向右移動嗎?

node

用於但未在任何地方聲明。

並希望您將其發布,然后發布整個內容。

同樣,當您的問題返回false時。 您的代碼返回真值的可能性要大得多(從技術上講,不應該僅僅因為num> this.n而返回真或左)。 因此,您的第一個問題是樹的構建,一旦得到錯誤,修復錯誤后,就可以修復搜索。

如果這不是單身漢或類似的東西:使用實現Red-Black-Tree的TreeSet

Set<Number> numbers = new TreeSet<Number>();
numbers.add(...);

if (numbers.contains(...)) {
  ...
}
  1. 在BST類中,可以將搜索和插入功能與一個根Node一起保留。您也將Node內部變量保留在BST中,這很容易引起混淆。
    2.如果將null-check添加到insert函數,則不需要其他的enter函數。
    3.同樣,您的搜索功能完全錯誤,因為您僅在第一級檢查是否相等。 您必須在左右兩邊遞歸地進行操作,直到找到密鑰或節點用完為止。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM