Java中的红黑树规则执行

时间:2015-03-18 23:14:08

标签: java tree red-black-tree

我正在尝试用Java实现红黑树。要做到这一点,我允许每个插入发生就好像它是一个BST然后插入后我预先遍历树并检查每个节点(我称之为Word,因为我正在使用它进行字典应用程序)红黑规则得到满足。到目前为止它看起来像这样

private void checkRedBlackRules(Word w)
    {

        //Checking for Red-Red sequence
        Word leftChild = w.getLeft(); 
        Word rightChild = w.getRight();
        Word leftleftGC, leftrightGC, rightleftGC, rightrightGC;
        if(leftChild != null)
        {
            leftleftGC = leftChild.getLeft();
            leftrightGC = leftChild.getRight();
        }
        else
        {
            leftleftGC = null;
            leftrightGC = null;
        }
        if(rightChild != null)
        {
            rightleftGC = rightChild.getLeft();
            rightrightGC = rightChild.getRight();
        }
        else
        {
            rightleftGC = null;
            rightrightGC = null;
        }
        try
        {
            if(leftChild.isRed() && leftleftGC.isRed())
            {
                rotateRight(w, leftChild, leftleftGC);
            }
        }
        catch(NullPointerException e) {}
        try
        {
            if(leftChild.isRed() && leftrightGC.isRed())
            {

            }
        }
        catch(NullPointerException e) {}
        try
        {
            if(rightChild.isRed() && rightleftGC.isRed())
            {

            }
        }
        catch(NullPointerException e) {}
        try
        {
            if(rightChild.isRed() && rightrightGC.isRed())
            {
                rotateLeft(w, leftChild, leftrightGC);
            }
        }
        catch(NullPointerException e) {}
        if(w.getLeft() != null)
            checkRedBlackRules(w.getLeft());
        if(w.getRight() != null)
            checkRedBlackRules(w.getRight());
    }

    private void rotateLeft(Word parent, Word child, Word grandChild)
    {
        child = parent;
        child.setLeft(parent);
        child.setRight(grandChild);
    }
    private void rotateRight(Word parent, Word child, Word grandChild)
    {
        child = parent;
        child.setLeft(grandChild);
        child.setRight(parent);
    }

但是,当我尝试向树中添加两个以上的元素时,它会陷入无限循环,直到出现StackOverflow错误。

1 个答案:

答案 0 :(得分:0)

没有详细介绍所有逻辑,旋转函数对我来说看起来不正确:

private void rotateLeft(Word parent, Word child, Word grandChild)
{
    child = parent;
    child.setLeft(parent);
    child.setRight(grandChild);
}

未使用child参数,而是立即将其设置为父参数。这意味着当你调用child.setLeft(parent)时,你将原始父级的左子项设置为自身,我认为这是导致无限循环的原因(因此堆栈溢出)。