不适用于未知原因的方法

时间:2013-03-09 21:52:37

标签: java binary-search-tree

所以,我正在自己实现二进制搜索树。在这样做的过程中,我遇到了一个不寻常的问题,我不知道它为什么会发生。

setNode方法:

// Sets the Node at the specified Index
public void setNode(int index, NodeInterface<E> node)
{
    if(index < 0 || index >= degree)
        throw new ArrayIndexOutOfBoundsException("Index: " + index + ", Size: " + nodes.size());

    nodes.set(index, (Node<E>) node);
}

变量节点是节点的数组列表,如果这很重要的话。

现在这就是事情开始变得混乱的地方,正是发生错误的地方。它位于 BinaryNode 类中的 addDescendant 方法中,它扩展了 Node 类。

addDescendant方法:

// Adds the specified Descendant to this Node
public boolean addDescendant(BinaryNode<E> node)
{
        // Determine Node Type
        if(compareTo(node) > 0) // Make Left Child
        {
            if(hasLeftChild())
                return getLeftChild().addDescendant(node);
            else
            {
                setNode(0, node); // Link Parent to Child
                // ^^^ Works Fine ^^^
                node.setNode(1, hasRightChild() ? getRightChild() : this); // Link Child to Parent or Sibling
                // ^^^ Does not Work ^^^

                return true;
            }
        }
        else if(compareTo(node) < 0) // Make Right Child
        {
            if(hasRightChild()) // Node already has a Right Child
                return getRightChild().addDescendant(node);
            else // Node does not have a Right Child
            {
                if(hasLeftChild())
                {
                    getLeftChild().setNode(1, node); // Link Sibling to Sibling
                    // ^^^ Does not Work ^^^
                }
                else
                {
                    setNode(0, node); // Link Parent to Child for the time being
                    // ^^^ Works Fine ^^^
                }

                node.setNode(1, this); // Link Child to Parent
                // ^^^ Does not Work ^^^

                return true;
            }
        }
        else // Duplicate Node
            return false;
    }

这里要注意的两个重要事项是 setNode 的使用。当我使用索引0时它工作正常,但是当我使用索引1时它不起作用。

我没有收到任何错误或警告,代码似乎应该运行,但结果并不是我所期待的。

该方法没有正确设置正确的节点,尽管它使用相同的方法来设置左节点,并且工作正常。

我希望我已经提供了足够的信息,我不想用代码轰炸所有人。

无关注:
如果您对我的树的连接感到困惑,那是因为它不是典型的二进制搜索树。但是,树的实际结构无关紧要。

1 个答案:

答案 0 :(得分:0)

信息不多。但我会尝试:
我认为你的树比二元更加一元 如果索引为1,则表示节点的右子节点 但也标志着一个节点的父节点,逻辑似乎 某种程度上打破了我。

第二件事是addDescendant的“让左孩子”部分: 可能会发生超过2个节点具有“根”节点 连接到他们的索引1。

addDescendant的'生孩子'部分:
getLeftChild().setNode(1, node); 更改子节点的节点而无需进一步检查 (通过不使用其addDescendant方法)不是一个好主意。

相关问题