简体   繁体   English

插入和搜索二进制搜索树

[英]Inserting and searching a Binary Search Tree

I am having trouble with my BST. 我的BST遇到了麻烦。 The BST which I am supposed to build has an implicit 'rank' in which the Nodes are sorted by. 我应该构建的BST具有隐含的“排名”,其中节点按顺序排序。 For instance, when inserting a new Node I am given a value to store in the Node and the rank in which to insert it. 例如,当插入新节点时,我被赋予一个值以存储在节点中以及插入它的等级。 In other words the BST is supposed to store a sequence. 换句话说,BST应该存储一个序列。 My insert function appears to work but small bugs appear occasionally and the select function throws a NullPointerException when it should not. 我的插入函数似乎工作但偶尔出现小错误,而select函数抛出NullPointerException时它不应该。

Node.java Node.java

RBST.java RBST.java

RBSTTest.java RBSTTest.java

public void insertNormal(int team, int rank)
{
    root = insertNormal(root, team, rank);
}

 /**
 * Insert the data team at position rank into node T. This is the normal
 * insert routine without any balancing.
 */
private Node insertNormal(Node T, int team, int rank)
{
    assert (rank >= 1 && rank <= T.getSize() + 1) : "rank should be between 1 and size of the tree <"
        + (T.getSize() + 1) + ">";

    if (T == null)
    {
        return new Node(team);
    }

    if (getRank(T) >= rank)
    {
        T.setLeft(insertNormal(T.getLeft(), team, rank));
    }
    else
    {
        T.setRight(insertNormal(T.getRight(), team, rank));
    }
    T.incSize();

    return T;
}


public Node select(int rank)
{
    return select(root, rank);
}

/**
 * The select method that returns the node in the tree at position rank.
 */
private Node select(Node T, int rank)
{
    if (T == null || getRank(T) == rank)
        return T;

    assert (rank >= 1 && rank <= T.getSize()) : "rank should be between 1 and size of the tree <" + T.getSize()
        + "> ";

    if (getRank(T) > rank)
        T = T.getLeft();
    else
        T = T.getRight();

    return select(T, rank);
}

public int getRank(Node T)
{
    return (T.getLeft() == null ? 1 : T.getLeft().getSize() + 1);
}

The binary search tree is constructed a bit strangely. 二叉搜索树的构造有点奇怪。 Apparently you know the rank of the teams beforehand. 显然你事先知道球队的级别。 In that case, you would normally store the rank with the team in the Node . 在这种情况下,您通常会将团队中的排名存储在Node Then you can easily retrieve the rank later. 然后您可以在以后轻松检索排名。 That way, you are also not forced to add the teams in order of their ranks. 这样,您也不会被迫按照他们的排名添加团队。

Your current getRank() method currently does not actually retrieve the rank. 您当前的getRank()方法当前并未实际检索排名。 Note that if you add teams in order of their rank now, you will get a very lob-side tree with the sub-tree always on the right side, with the left side always null . 请注意,如果您现在按照其排名顺序添加团队,您将获得一个非常高的侧树,子树始终位于右侧,左侧始终为null That is also likely where your faults come from: getRank() will always return 1. 这也可能是你的错误来自: getRank()将始终返回1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM